24326140 upgrade LLVM to 3.8.1
authorStefan Teleman <stefan.teleman@oracle.com>
Thu, 28 Jul 2016 16:25:34 -0700
changeset 6512 92717ce71105
parent 6511 d283aa33e131
child 6513 ea2097ba7d67
24326140 upgrade LLVM to 3.8.1 24326159 upgrade clang to 3.8.1 22902339 memory corruption caused by undefined behavior in LLVM IR Module 22777179 implement [ -mtune= -march= -mcpu= ] in clang SPARC 22778085 LLVM is using %icc when it should be using %xcc 22778089 the SPARCV9 IS implementation is incomplete 22778098 LLVM should emit proc identifiers in SPARC assembler (capabilities) 22778650 clang should support OpenMP because it can 22859423 llvm CodeGen on Intel emits a bogus .ctors section 22902355 clang CodeGen is affected by 22902339 23701635 clang produces amd64 opcodes, but calls 32-bit assembler by default 23593143 lli JIT bitcode parsing creates a main function with wrong argc/argv 21759660 clang packages should include the scan-view and scan-build utilities 23854357 clang should check for GNU ld 17867434 clang crashed in LEXER 24306550 clang crashes in llvm::Twine::toStringRef 24311726 clang's Perl and Python utilities should not use #!/usr/bin/env 24312028 llvm::Twine needs copy constructors and assignment operators 24312221 classes must be CopyConstructible, CopyAssignable, MoveConstructible ... 24314621 LLVM should build using the new CMake based build system 24314638 LLVM CommandLine subsystem is busted 24314687 static initialization of optimization passes doesn't work as intended 21870069 clang makes incorrect assumptions about anonymous namespace instantiation order 22643565 llvm's Google test harness needs some attention 24314745 clang should support PIE executables in Solaris
components/llvm/Makefile
components/llvm/Solaris/man1/FileCheck.1
components/llvm/Solaris/man1/bugpoint.1
components/llvm/Solaris/man1/clang.1
components/llvm/Solaris/man1/lit.1
components/llvm/Solaris/man1/llc.1
components/llvm/Solaris/man1/lli.1
components/llvm/Solaris/man1/llvm-ar.1
components/llvm/Solaris/man1/llvm-as.1
components/llvm/Solaris/man1/llvm-bcanalyzer.1
components/llvm/Solaris/man1/llvm-build.1
components/llvm/Solaris/man1/llvm-config.1
components/llvm/Solaris/man1/llvm-cov.1
components/llvm/Solaris/man1/llvm-diff.1
components/llvm/Solaris/man1/llvm-dis.1
components/llvm/Solaris/man1/llvm-dwarfdump.1
components/llvm/Solaris/man1/llvm-extract.1
components/llvm/Solaris/man1/llvm-lib.1
components/llvm/Solaris/man1/llvm-link.1
components/llvm/Solaris/man1/llvm-nm.1
components/llvm/Solaris/man1/llvm-profdata.1
components/llvm/Solaris/man1/llvm-readobj.1
components/llvm/Solaris/man1/llvm-stress.1
components/llvm/Solaris/man1/llvm-symbolizer.1
components/llvm/Solaris/man1/opt.1
components/llvm/Solaris/man1/tblgen.1
components/llvm/clang-build.p5m
components/llvm/clang.p5m
components/llvm/cxa_finalize/Makefile
components/llvm/llvm-build.p5m
components/llvm/llvm.p5m
components/llvm/patches/000-AutoRegen.sh.patch
components/llvm/patches/000-solaris-LLVM-libLLVMTransforms.patch
components/llvm/patches/001-Makefile.config.in.patch
components/llvm/patches/001-solaris-LLVM-libLLVMCodegen.patch
components/llvm/patches/002-Makefile.patch
components/llvm/patches/002-solaris-LLVM-libLLVMSupport.patch
components/llvm/patches/003-Makefile.rules.patch
components/llvm/patches/003-solaris-LLVM-ADT.patch
components/llvm/patches/004-configure.ac.patch
components/llvm/patches/004-solaris-LLVM-libIR.patch
components/llvm/patches/005-Makefile.patch
components/llvm/patches/005-solaris-LLVM-libLLVMMC.patch
components/llvm/patches/006-clang-D10272.patch
components/llvm/patches/006-solaris-LLVM-libLLVMAnalysis.patch
components/llvm/patches/007-TemplateBase.patch
components/llvm/patches/007-solaris-LLVM-libLLVMLibDriver.patch
components/llvm/patches/008-DeclTemplate.patch
components/llvm/patches/008-solaris-clang-libclangAST.patch
components/llvm/patches/009-InitPreprocessor.patch
components/llvm/patches/009-solaris-clang-libclangSema.patch
components/llvm/patches/010-linker-mapfiles.patch
components/llvm/patches/010-solaris-clang-libclangBasic.patch
components/llvm/patches/011-gxx-abi-version.patch
components/llvm/patches/011-solaris-clang-libclangCodeGen.patch
components/llvm/patches/012-TypeLocBuilder.cpp.patch
components/llvm/patches/012-solaris-clang-libclangDriver.patch
components/llvm/patches/013-llvm-alignments.patch
components/llvm/patches/013-solaris-clang-libclangFrontend.patch
components/llvm/patches/014-clang-gcc-toolchain.patch
components/llvm/patches/014-solaris-clang-libclangLex.patch
components/llvm/patches/015-llvm-clang-memory-corruption.patch
components/llvm/patches/015-solaris-clang-tools-driver.patch
components/llvm/patches/016-llvm-21851513-memory-corruption.patch
components/llvm/patches/016-solaris-clang-tools-libclang.patch
components/llvm/patches/017-lli-21870067.patch
components/llvm/patches/017-solaris-clang-tools-tablegen.patch
components/llvm/patches/018-21870283-llvm-GetArgumentVector.patch
components/llvm/patches/018-solaris-LLVM-utils-tablegen.patch
components/llvm/patches/019-21870099-clang.patch
components/llvm/patches/019-solaris-LLVM-utils-filecheck.patch
components/llvm/patches/020-21874221-clang-llvm-sparc-assembler.patch
components/llvm/patches/020-solaris-utils-googletest.patch
components/llvm/patches/021-llvm-ilist-iterator-22031298.patch
components/llvm/patches/021-solaris-LLVM-tools-llc.patch
components/llvm/patches/022-google-test-harness-22643565.patch
components/llvm/patches/022-solaris-LLVM-tools-llvm-as.patch
components/llvm/patches/023-Makefile.config.in.patch
components/llvm/patches/023-solaris-LLVM-tools-llvm-config.patch
components/llvm/patches/024-solaris-LLVM-tools-llvm-dis.patch
components/llvm/patches/025-solaris-LLVM-tools-opt.patch
components/llvm/patches/026-solaris-LLVM-tools-bugpoint.patch
components/llvm/patches/027-solaris-LLVM-libsupport-unittests.patch
components/llvm/patches/028-solaris-LLVM-libTableGen.patch
components/llvm/patches/029-solaris-LLVM-libTarget-X86.patch
components/llvm/patches/030-solaris-exception-demo.patch
components/llvm/patches/031-solaris-build-system.patch
components/llvm/patches/032-solaris-LLVM-libTarget-SPARC.patch
components/llvm/patches/033-solaris-LLVM-JIT.patch
components/llvm/patches/034-solaris-clang-LLVM-python-perl-utils.patch
--- a/components/llvm/Makefile	Thu Jul 28 16:15:45 2016 -0700
+++ b/components/llvm/Makefile	Thu Jul 28 16:25:34 2016 -0700
@@ -23,27 +23,31 @@
 # Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
 #
 export PARFAIT_BUILD=no
-BUILD_BITS= 64
-COMPILER= gcc
+BUILD_BITS=64
+COMPILER=gcc
+
 include ../../make-rules/shared-macros.mk
 
 COMPONENT_NAME=		llvm
-COMPONENT_VERSION=	3.6.2
+COMPONENT_VERSION=	3.8.1
 COMPONENT_PROJECT_URL=	http://llvm.org/
+COMPONENT_SRC=		$(COMPONENT_NAME)
+COMPONENT_BUGDB=	utility/llvm
+
 COMPONENT_SRC=		$(COMPONENT_NAME)-$(COMPONENT_VERSION)
-COMPONENT_SRC_NAME =	$(COMPONENT_SRC).src
+COMPONENT_SRC_NAME=	$(COMPONENT_SRC).src
 COMPONENT_ARCHIVE=	$(COMPONENT_SRC_NAME).tar.xz
 COMPONENT_ARCHIVE_HASH=	\
-    sha256:f60dc158bfda6822de167e87275848969f0558b3134892ff54fced87e4667b94
+    sha256:6e82ce4adb54ff3afc18053d6981b6aed1406751b8742582ed50f04b5ab475f9
 COMPONENT_ARCHIVE_URL=	$(COMPONENT_PROJECT_URL)/releases/$(COMPONENT_VERSION)/$(COMPONENT_ARCHIVE)
 
-TPNO=			24358
+TPNO=			28049
 
 COMPONENT_NAME_1 =	clang
 COMPONENT_SRC_1 =	cfe-$(COMPONENT_VERSION).src
 COMPONENT_ARCHIVE_1 =	$(COMPONENT_SRC_1).tar.xz
 COMPONENT_ARCHIVE_HASH_1 = \
-	sha256:ae9180466a23acb426d12444d866b266ff2289b266064d362462e44f8d4699f3
+	sha256:4cd3836dfb4b88b597e075341cae86d61c63ce3963e45c7fe6a8bf59bb382cdf
 COMPONENT_ARCHIVE_URL_1 = $(COMPONENT_PROJECT_URL)/releases/$(COMPONENT_VERSION)/$(COMPONENT_ARCHIVE_1)
 
 COMPONENT_POST_UNPACK_ACTION = \
@@ -54,48 +58,74 @@
 	 $(CP) -rp $(COMPONENT_SRC_1) \
 	    $(COMPONENT_SRC)/tools/$(COMPONENT_NAME_1) )
 
-COMPONENT_PRE_CONFIGURE_ACTION = \
-	 ( cd $(SOURCE_DIR) ; \
-	 $(CHMOD) 0755 ./autoconf/AutoRegen.sh ; \
-	 ./autoconf/AutoRegen.sh )
-
-COMPONENT_POST_BUILD_ACTION = \
-      if test -d $(COMPONENT_DIR)/cxa_finalize ; then \
-      $(GMAKE) -C $(COMPONENT_DIR)/cxa_finalize build ; \
-      fi
-
-COMPONENT_POST_INSTALL_ACTION = \
-	if test -d $(COMPONENT_DIR)/cxa_finalize ; then \
-	$(GMAKE) -C $(COMPONENT_DIR)/cxa_finalize install ; \
-	fi;
-
 # Depends on S12-only changes in gcc; might be able to deal with later,
 # but avoid publishing while this is under investigation.
 ifeq ($(BUILD_TYPE), evaluation)
-BUILD_64=
-INSTALL_64=
-PUBLISH_STAMP=
+  BUILD_64=
+  INSTALL_64=
+  PUBLISH_STAMP=
 endif
 
-TEST_TARGET=
+BUILD_STYLE = cmake
+CLONEY = echo
+GNUCP = /usr/gnu/bin/cp
+
 include $(WS_MAKE_RULES)/common.mk
 
 PATCH_LEVEL := 0
 DEBUG_BUILD := 0
 GCC_VERSION := 4.9
+HAVE_SPHINX := 0
 
-# We need GCC version 4.9, and not another version.
+export PATH=/usr/gnu/bin:/usr/bin:/usr/perl5/$(PERL_VERSION)/bin
+
+# We use GCC version 4.9.3, and not another version for now.
 CC=$(USRDIR)/gcc/$(GCC_VERSION)/bin/gcc
 CXX=$(USRDIR)/gcc/$(GCC_VERSION)/bin/g++
 
+# We're building with CMake
+CMAKE=/usr/bin/cmake
+CMAKE_VERSION := $(shell $(CMAKE) --version 2>&1 | head -n1 \
+  | $(GSED) 's/cmake version \{1,\}//g')
+CMAKE_MAJOR_VERSION := $(shell echo $(CMAKE_VERSION) | cut -f1 -d'.')
+CMAKE_MINOR_VERSION := $(shell echo $(CMAKE_VERSION) | cut -f2 -d'.')
+CMAKE_MICRO_VERSION := $(shell echo $(CMAKE_VERSION) | cut -f3 -d'.')
+
+# CMake prior to 3.6.0 does not define CMAKE_HOST_SOLARIS.
+# In that case, we pass it in CMAKE_OPTIONS.
+CMAKE_NEEDS_SOLARIS_HOST := 0
+ifeq ($(shell expr $(CMAKE_MAJOR_VERSION) \<= 3 \& \
+		    $(CMAKE_MINOR_VERSION) \<= 5),1)
+  CMAKE_NEEDS_SOLARIS_HOST = 1
+endif
+
+# All of these shoujld probably be in shared-macros.mk
+CMAKE_INSTALL_BINDIR.32 = bin
+CMAKE_INSTALL_BINDIR.64 = bin/$(MACH64)
+CMAKE_INSTALL_BINDIR = $(CMAKE_INSTALL_BINDIR.$(BITS))
+
+CMAKE_INSTALL_LIBDIR.32 = lib
+CMAKE_INSTALL_LIBDIR.64 = lib/$(MACH64)
+CMAKE_INSTALL_LIBDIR = $(CMAKE_INSTALL_LIBDIR.$(BITS))
+
+CMAKE_INSTALL_LIBEXECDIR.32 = libexec
+CMAKE_INSTALL_LIBEXECDIR.64 = libexec/$(MACH64)
+CMAKE_INSTALL_LIBEXECDIR = $(CMAKE_INSTALL_LIBEXECDIR.$(BITS))
+
+CMAKE_INSTALL_INCLUDEDIR = include
+CMAKE_INSTALL_DATADIR = share
+CMAKE_INSTALL_DATAROOTDIR = share
+
 # We need the specific C++ runtime that clang/llvm was built and
 # linked with, and not some random and incompatible stuff from
 # /usr/lib.
-LLVM_RUNPATH_32 = $(USRDIR)/gcc/$(GCC_VERSION)/lib
-LLVM_RUNPATH_64 = $(USRDIR)/gcc/$(GCC_VERSION)/lib/$(MACH64)
+LLVM_RUNPATH_32 = /usr/gcc/$(GCC_VERSION)/lib
+LLVM_RUNPATH_64 = /usr/gcc/$(GCC_VERSION)/lib/$(MACH64)
 LLVM_RUNPATH = $(LLVM_RUNPATH_$(BITS))
 
-# -O0 for now. Ideally we want -O2.
+# -O0. GCC on SPARC dies with an out-memory error in cc1plus when
+# building with either -O1 or -O2 (32-bit). If it manages to get
+# through with -O1 or -O2 (64-bit), the resulting bits are unusable.
 OFLAG="-O0"
 GFLAG=""
 
@@ -104,24 +134,110 @@
   GFLAG="-g3"
 endif
 
-export PATH=$(GNUBIN):$(USRDIR)/xpg4/bin:$(USRBINDIR):$(USRDIR)/perl5/5.16/bin
-
 # Because LLVM's install target doesn't install everything that
 # needs to be installed.
 EXTRA_INSTALL_BITS=llvm-lto arcmt-test c-arcmt-test c-index-test diagtool
-LLVM_BINDIR=$(BUILD_DIR_64)/Release/bin
+LLVM_INSTALL_BINDIR.32=$(PROTOUSRBINDIR)
+LLVM_INSTALL_BINDIR.64=$(PROTOUSRBINDIR64)
+LLVM_INSTALL_BINDIR=$(LLVM_INSTALL_BINDIR.$(BITS))
+LLVM_BINDIR=$(BUILD_DIR_$(BITS))/bin
+
+INSTALL_CXA_FINALIZE := 0
+ifeq ($(SOLARIS_11_ONLY),)
+  INSTALL_CXA_FINALIZE = 1
+endif
 
-ifeq ($(DEBUG_BUILD), 1)
-  LLVM_BINDIR=$(BUILD_DIR_64)/Debug+Asserts+Checks/bin
-endif
+SCAN_VIEW_FILES=Reporter.py ScanView.py
+CLANG_FORMAT_FILES=clang-format-diff.py clang-format-sublime.py \
+		   clang-format.py
+LLVM_MAN_FILES=FileCheck.1 bugpoint.1 clang.1 lit.1 llc.1 lli.1 \
+	       llvm-ar.1 llvm-as.1 llvm-bcanalyzer.1 llvm-build.1 \
+	       llvm-config.1 llvm-cov.1 llvm-diff.1 llvm-dis.1 \
+	       llvm-dwarfdump.1 llvm-extract.1 llvm-lib.1 llvm-link.1 \
+	       llvm-nm.1 llvm-profdata.1 llvm-readobj.1 llvm-stress.1 \
+	       llvm-symbolizer.1 opt.1 tblgen.1
+
+COMPONENT_POST_BUILD_ACTION = \
+      if test -d $(COMPONENT_DIR)/cxa_finalize ; then \
+      /usr/gnu/bin/touch $(COMPONENT_DIR)/cxa_finalize/.patched ; \
+      /usr/gnu/bin/touch $(COMPONENT_DIR)/cxa_finalize/.prep ; \
+      $(GMAKE) -C $(COMPONENT_DIR)/cxa_finalize build ; \
+      /usr/gnu/bin/touch $(COMPONENT_DIR)/cxa_finalize/.built ; \
+      fi
+
+COMPONENT_POST_INSTALL_ACTION = \
+	if test -d $(COMPONENT_DIR)/cxa_finalize ; then \
+	$(GMAKE) -C $(COMPONENT_DIR)/cxa_finalize install ; \
+	/usr/gnu/bin/touch $(COMPONENT_DIR)/cxa_finalize/.installed ; \
+	fi;
 
 COMPONENT_POST_INSTALL_ACTION += \
 	list1='$(EXTRA_INSTALL_BITS)' ; for f in $$list1 ; do \
-	    $(INSTALL) --mode=755 $(LLVM_BINDIR)/$$f $(PROTOUSRBINDIR)/$$f ; \
-	done;
+	    $(INSTALL) --mode=755 $(LLVM_BINDIR)/$$f \
+			$(LLVM_INSTALL_BINDIR)/$$f ; \
+	done ;
+
+COMPONENT_POST_INSTALL_ACTION += \
+	$(MKDIR) \
+	  $(PROTOUSRLIBDIR)/python$(PYTHON_VERSION)/vendor-packages ; \
+	list2='$(SCAN_VIEW_FILES)' ; for f in $$list2 ; do \
+	$(INSTALL) --mode=644 $(PROTOUSRSHAREDIR)/scan-view/$$f \
+	  $(PROTOUSRLIBDIR)/python$(PYTHON_VERSION)/vendor-packages/$$f ; \
+	done ;
+
+COMPONENT_POST_INSTALL_ACTION += \
+	list3='$(CLANG_FORMAT_FILES)' ; for f in $$list3 ; do \
+	  $(INSTALL) --mode=644 $(PROTOUSRSHAREDIR)/clang/$$f \
+	    $(PROTOUSRLIBDIR)/python$(PYTHON_VERSION)/vendor-packages/$$f ; \
+	done ;
+
+COMPONENT_POST_INSTALL_ACTION += \
+	cd $(COMPONENT_DIR) ; \
+	$(GNUCP) -rpd $(PROTOUSRLIBDIR64)/clang $(PROTOUSRLIBDIR)/ ;
+
+COMPONENT_POST_INSTALL_ACTION += \
+	cd $(PROTOUSRLIBDIR) ; \
+	$(PYTHON) -m compileall . ;
 
-# No ASLR for compilers.
-ASLR_MODE = $(ASLR_DISABLE)
+COMPONENT_POST_INSTALL_ACTION += \
+	cd $(COMPONENT_DIR) ; \
+	$(MKDIR) $(PROTOUSRSHAREMAN1DIR) ; \
+	list4='$(LLVM_MAN_FILES)' ; for f in $$list4 ; do \
+	  $(INSTALL) --mode=644 $(COMPONENT_DIR)/Solaris/man1/$$f \
+	    $(PROTOUSRSHAREMAN1DIR)/$$f ; \
+	done ;
+
+ifeq ($(INSTALL_CXA_FINALIZE),1)
+COMPONENT_POST_INSTALL_ACTION += \
+	$(INSTALL) --mode=644 \
+	  $(COMPONENT_DIR)/cxa_finalize/cxa_finalize-32.o \
+	  $(PROTOUSRLIBDIR)/clang/cxa_finalize.o ; \
+	$(INSTALL) --mode=644 \
+	  $(COMPONENT_DIR)/cxa_finalize/cxa_finalize_pic-32.o \
+	  $(PROTOUSRLIBDIR)/clang/cxa_finalize_pic.o ; \
+	$(INSTALL) --mode=644 \
+	  $(COMPONENT_DIR)/cxa_finalize/cxa_finalize-64.o \
+	  $(PROTOUSRLIBDIR)/clang/$(MACH64)/cxa_finalize.o ; \
+	$(INSTALL) --mode=644 \
+	  $(COMPONENT_DIR)/cxa_finalize/cxa_finalize_pic-64.o \
+	  $(PROTOUSRLIBDIR)/clang/$(MACH64)/cxa_finalize_pic.o ;
+endif
+
+# Results output is slightly different on Intel vs. SPARC.
+# Not enabled just yet because of problems with the way opt
+# and FileCheck emit and parse the test case results.
+COMPONENT_TEST_MASTER = \
+	$(COMPONENT_TEST_RESULTS_DIR)/results-$(MACH).master
+
+# Do not change the order of these regexp transforms.
+COMPONENT_TEST_TRANSFORMS += \
+    '-e "/gmake -f/d"' \
+    '-e "/gmake/d"' \
+    '-e "/--color=/d"' \
+    '-e "/Entering/d"' \
+    '-e "/Leaving/d"' \
+    '-e "/Built target/d"' \
+    '-e "/Nothing to be done/d"'
 
 # GCC options used:
 # -ftree-vectorize | -fno-tree-vectorize:
@@ -196,8 +312,9 @@
 #
 # -mno-sse3 -mno-ssse3:
 # Do not use SSE3/SSSE3 instructions on Intel. These might not be
-# available. Building for Opteron - which implies SSE2 - is adequate
-# for performance purposes.
+# available and they always come with side-effects.
+# Building for Opteron - which implies SSE2 - is adequate for
+# performance purposes.
 
 CFLAGS = -m$(BITS) $(GFLAG) $(OFLAG) -pthread -std=c99 -fno-strict-aliasing
 CFLAGS += -fno-tree-slp-vectorize -fno-tree-vectorize
@@ -205,9 +322,15 @@
 CFLAGS += -Wall -Wcast-align -Wno-long-long -Woverflow
 CFLAGS += -Wstack-protector -fdata-sections -fstack-protector-all
 CFLAGS += -fkeep-static-consts -ffunction-sections
-CFLAGS += -Wl,-z -Wl,relax=common -Wl,-z -Wl,relax=secadj
-CFLAGS += -Wl,-z -Wl,relax=transtls -Wl,-R -Wl,$(LLVM_RUNPATH)
+CFLAGS += -Wl,-z -Wl,relax=common
+CFLAGS += -Wl,-z -Wl,relax=secadj
+CFLAGS += -Wl,-z -Wl,relax=transtls
+CFLAGS += -Wl,-z -Wl,relax=symbound
+CFLAGS += -Wl,-R -Wl,$(LLVM_RUNPATH)
 CFLAGS.i386 += -mtune=opteron -mno-sse3 -mno-ssse3 -fno-common
+ifeq ($(DEBUG_BUILD),1)
+  CFLAGS.i386 += -fno-omit-frame-pointer
+endif
 CFLAGS.sparc += -mtune=ultrasparc -mcpu=ultrasparc -mvis -mhard-float
 CFLAGS.sparc += -mptr$(BITS) -fdata-sections -falign-functions=8
 CFLAGS.sparc += -mno-unaligned-doubles -mimpure-text
@@ -220,18 +343,22 @@
 CXXFLAGS += -Wall -Wcast-align -Wno-long-long -Woverflow
 CXXFLAGS += -Wstack-protector -fkeep-static-consts
 CXXFLAGS += -std=c++11 -fdata-sections -ffunction-sections
-CXXFLAGS += -Wl,-z -Wl,relax=common -Wl,-z -Wl,relax=secadj
-CXXFLAGS += -Wl,-z -Wl,relax=transtls -Wl,-R -Wl,$(LLVM_RUNPATH)
+CXXFLAGS += -Wl,-z -Wl,relax=common
+CXXFLAGS += -Wl,-z -Wl,relax=secadj
+CXXFLAGS += -Wl,-z -Wl,relax=transtls
+CXXFLAGS += -Wl,-z -Wl,relax=symbound
+CXXFLAGS += -Wl,-z -Wl,relax=comdat
+CXXFLAGS += -Wl,-R -Wl,$(LLVM_RUNPATH)
 CXXFLAGS.sparc += -mptr$(BITS)
 CXXFLAGS += $(CFLAGS.$(MACH))
 
-CPPFLAGS = -D_GNU_SOURCE -DLLVM_SOLARIS -I$(USRGNUDIR)/include
+CPPFLAGS = -D_GNU_SOURCE -DLLVM_SOLARIS -I/usr/gnu/include
 
-ifeq ($(DEBUG_BUILD), 1)
+ifeq ($(DEBUG_BUILD),1)
   CPPFLAGS += -D_DEBUG
 endif
 
-CPPFLAGS += -D_REENTRANT -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64
+CPPFLAGS += -D_REENTRANT -D_LARGEFILE64_SOURCE
 CPPFLAGS += -D_FILE_OFFSET_BITS=64 -D__EXTENSIONS__=1
 CPPFLAGS += -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS
 CPPFLAGS += -D__STDC_LIMIT_MACROS -DHAVE_POSIX_MEMALIGN
@@ -240,68 +367,146 @@
 CPPFLAGS.sparc = -DLLVM_SPARC
 CPPFLAGS += $(CPPFLAGS.$(MACH))
 
-LLVM_LIBEXECDIR_32 = $(USRDIR)/libexec
-LLVM_LIBEXECDIR_64 = $(USRDIR)/libexec/$(MACH64)
+LLVM_LIBEXECDIR_32 = /usr/libexec
+LLVM_LIBEXECDIR_64 = /usr/libexec/$(MACH64)
 LLVM_LIBEXECDIR = $(LLVM_LIBEXECDIR_$(BITS))
 
-CONFIGURE_OPTIONS += --libexecdir=$(LLVM_LIBEXECDIR)
-CONFIGURE_OPTIONS += --sharedstatedir=/tmp
-CONFIGURE_OPTIONS += --localstatedir=$(VARDIR)
-CONFIGURE_OPTIONS += --enable-compiler-version-checks
-CONFIGURE_OPTIONS += --enable-clang-static-analyzer
+LIBFFI_INCDIR_32 = /usr/lib/libffi-3.0.9/include
+LIBFFI_INCDIR_64 = /usr/lib/$(MACH64)/libffi-3.0.9/include
+LIBFFI_INCDIR = $(LIBFFI_INCDIR_$(BITS))
+
+LIBFFI_LIBDIR_32 = /usr/lib
+LIBFFI_LIBDIR_64 = /usr/lib/$(MACH64)
+LIBFFI_LIBDIR = $(LIBFFI_LIBDIR_$(BITS))
+
+# -Bdirect and -M /usr/lib/ld/map.noexbss break SPARC builds.
+LD_B_DIRECT =
+LD_OPTIONS = -M /usr/lib/ld/map.noexstk
+LD_OPTIONS += -M /usr/lib/ld/map.pagealign
+LD_OPTIONS_SO = $(LD_Z_DEFS) $(LD_DEF_LIBS)
 
-ifeq ($(DEBUG_BUILD), 1)
-  CONFIGURE_OPTIONS += --enable-assertions
-  CONFIGURE_OPTIONS += --disable-optimized
-  CONFIGURE_OPTIONS += --enable-expensive-checks
-  CONFIGURE_OPTIONS += --enable-debug-runtime
-  CONFIGURE_OPTIONS += --enable-debug-symbols
-else
-  CONFIGURE_OPTIONS += --disable-assertions
-  CONFIGURE_OPTIONS += --enable-optimized
-  CONFIGURE_OPTIONS += --disable-expensive-checks
-  CONFIGURE_OPTIONS += --disable-debug-runtime
-  CONFIGURE_OPTIONS += --disable-debug-symbols
+CMAKE_OPTIONS = -DCMAKE_C_COMPILER:FILEPATH=$(CC)
+CMAKE_OPTIONS += -DCMAKE_CXX_COMPILER:FILEPATH=$(CXX)
+CMAKE_OPTIONS += -DCMAKE_C_CFLAGS:STRING="$(CPPFLAGS) $(CFLAGS)"
+CMAKE_OPTIONS += -DCMAKE_CXX_FLAGS:STRING="$(CPPFLAGS) $(CXXFLAGS)"
+CMAKE_OPTIONS += -DCMAKE_EXE_LINKER_FLAGS:STRING="$(LDFLAGS)"
+CMAKE_OPTIONS += -DCMAKE_INSTALL_PREFIX:FILEPATH=$(CMAKE_PREFIX)
+CMAKE_OPTIONS += -DCMAKE_AR:FILEPATH=/usr/bin/ar
+
+CMAKE_OPTIONS += -DCMAKE_INSTALL_BINDIR:STRING="$(CMAKE_INSTALL_BINDIR)"
+CMAKE_OPTIONS += -DCMAKE_INSTALL_LIBDIR:STRING="$(CMAKE_INSTALL_LIBDIR)"
+CMAKE_OPTIONS += -DCMAKE_INSTALL_LIBEXECDIR:STRING="$(CMAKE_INSTALL_LIBEXECDIR)"
+CMAKE_OPTIONS += -DCMAKE_INSTALL_INCLUDEDIR:STRING="$(CMAKE_INSTALL_INCLUDEDIR)"
+CMAKE_OPTIONS += -DCMAKE_INSTALL_DATADIR:STRING="$(CMAKE_INSTALL_DATADIR)"
+CMAKE_OPTIONS += -DCMAKE_INSTALL_DATAROOTDIR:STRING="$(CMAKE_INSTALL_DATAROOTDIR)"
+
+ifeq ($(MACH),sparc)
+  CMAKE_OPTIONS += -DLLVM_TARGETS_TO_BUILD:STRING="Sparc"
+endif
+ifeq ($(MACH),i386)
+  CMAKE_OPTIONS += -DLLVM_TARGETS_TO_BUILD:STRING="X86"
 endif
 
-CONFIGURE_OPTIONS += --enable-keep-symbols
-CONFIGURE_OPTIONS += --enable-jit
-CONFIGURE_OPTIONS += --disable-docs
-CONFIGURE_OPTIONS += --disable-doxygen
-CONFIGURE_OPTIONS += --enable-threads
-CONFIGURE_OPTIONS += --enable-pthreads
-CONFIGURE_OPTIONS += --enable-shared
-CONFIGURE_OPTIONS += --enable-zlib
-CONFIGURE_OPTIONS += --enable-pic
-CONFIGURE_OPTIONS += --enable-timestamps
-CONFIGURE_OPTIONS += --enable-backtraces
-CONFIGURE_OPTIONS += --enable-bindings=auto
-CONFIGURE_OPTIONS += --enable-libffi
-CONFIGURE_OPTIONS += --enable-terminfo
-CONFIGURE_OPTIONS += --disable-ltdl-install
-CONFIGURE_OPTIONS += --with-python=$(PYTHON)
+CMAKE_OPTIONS += -DCMAKE_MAKE_PROGRAM:STRING="/usr/bin/gmake"
+CMAKE_OPTIONS += -DCMAKE_ASM_COMPILER:STRING="/usr/gnu/bin/as"
+CMAKE_OPTIONS += -DCMAKE_INSTALL_RPATH:STRING="$(LLVM_RUNPATH)"
+CMAKE_OPTIONS += -DLLVM_BUILD_TOOLS:BOOL=ON
+CMAKE_OPTIONS += -DLLVM_INCLUDE_TOOLS:BOOL=ON
+CMAKE_OPTIONS += -DLLVM_BUILD_TESTS:BOOL=ON
+CMAKE_OPTIONS += -DLLVM_INCLUDE_TESTS:BOOL=ON
+CMAKE_OPTIONS += -DLLVM_ENABLE_THREADS:BOOL=ON
+CMAKE_OPTIONS += -DLLVM_BUILD_32_BITS:BOOL=OFF
+
+# CMake tries really hard to be too smart for its own good.
+ifeq ($(DEBUG_BUILD),1)
+  CMAKE_OPTIONS += -DCMAKE_BUILD_TYPE:STRING=Debug
+  CMAKE_OPTIONS += -DCMAKE_C_FLAGS_DEBUG:STRING="$(OFLAG) $(GFLAG)"
+  CMAKE_OPTIONS += -DCMAKE_CXX_FLAGS_DEBUG:STRING="$(OFLAG) $(GFLAG)"
+  CMAKE_OPTIONS += -DCMAKE_ASM_FLAGS_DEBUG:STRING="$(OFLAG) $(GFLAG)"
+  CMAKE_OPTIONS += -DCMAKE_ASM_FLAGS_RELWITHDEBINFO:STRING="$(OFLAG) $(GFLAG)"
+  CMAKE_OPTIONS += -DCMAKE_C_FLAGS_RELWITHDEBINFO:STRING="$(OFLAG) $(GFLAG)"
+  CMAKE_OPTIONS += -DCMAKE_CXX_FLAGS_RELWITHDEBINFO:STRING="$(OFLAG) $(GFLAG)"
+  CMAKE_OPTIONS += -DLLVM_BUILD_EXAMPLES:BOOL=ON
+  CMAKE_OPTIONS += -DLLVM_INCLUDE_EXAMPLES:BOOL=ON
+  CMAKE_OPTIONS += -DLLVM_ENABLE_ASSERTIONS:BOOL=ON
+  CMAKE_OPTIONS += -DLLVM_ENABLE_EXPENSIVE_CHECKS:BOOL=ON
+else
+  CMAKE_OPTIONS += -DCMAKE_BUILD_TYPE:STRING=Release
+  CMAKE_OPTIONS += -DCMAKE_C_FLAGS_DEBUG:STRING="$(OFLAG)"
+  CMAKE_OPTIONS += -DCMAKE_CXX_FLAGS_DEBUG:STRING="$(OFLAG)"
+  CMAKE_OPTIONS += -DCMAKE_ASM_FLAGS_DEBUG:STRING="$(OFLAG)"
+  CMAKE_OPTIONS += -DCMAKE_ASM_FLAGS_RELWITHDEBINFO:STRING="$(OFLAG)"
+  CMAKE_OPTIONS += -DCMAKE_C_FLAGS_RELWITHDEBINFO:STRING="$(OFLAG)"
+  CMAKE_OPTIONS += -DCMAKE_CXX_FLAGS_RELWITHDEBINFO:STRING="$(OFLAG)"
+  CMAKE_OPTIONS += -DLLVM_BUILD_EXAMPLES:BOOL=OFF
+  CMAKE_OPTIONS += -DLLVM_INCLUDE_EXAMPLES:BOOL=OFF
+  CMAKE_OPTIONS += -DLLVM_ENABLE_ASSERTIONS:BOOL=OFF
+  CMAKE_OPTIONS += -DLLVM_ENABLE_EXPENSIVE_CHECKS:BOOL=OFF
+endif
 
-ifeq ($(MACH),sparc)
-  CONFIGURE_OPTIONS += --with-extra-ld-options='-lkstat'
+CMAKE_OPTIONS += -DLLVM_ENABLE_EH:BOOL=ON
+CMAKE_OPTIONS += -DLLVM_ENABLE_PIC:BOOL=ON
+CMAKE_OPTIONS += -DLLVM_ENABLE_RTTI:BOOL=ON
+CMAKE_OPTIONS += -DLLVM_ENABLE_WARNINGS:BOOL=ON
+CMAKE_OPTIONS += -DLLVM_ENABLE_PEDANTIC:BOOL=ON
+CMAKE_OPTIONS += -DLLVM_ABI_BREAKING_CHECKS:STRING="FORCE_OFF"
+CMAKE_OPTIONS += -DLLVM_ENABLE_ZLIB:BOOL=ON
+CMAKE_OPTIONS += -DLLVM_ENABLE_FFI:BOOL=ON
+CMAKE_OPTIONS += -DFFI_INCLUDE_DIR:STRING=$(LIBFFI_INCDIR)
+CMAKE_OPTIONS += -DFFI_LIBRARY_DIR:STRING=$(LIBFFI_LIBDIR)
+
+ifeq ($(HAVE_SPHINX),1)
+  CMAKE_OPTIONS += -DSPHINX_EXECUTABLE:STRING="/usr/bin/sphinx-build"
+  CMAKE_OPTIONS += -DLLVM_ENABLE_SPHINX:BOOL=ON
+  CMAKE_OPTIONS += -DLLVM_BUILD_DOCS:BOOL=ON
+  CMAKE_OPTIONS += -DSPHINX_OUTPUT_HTML:BOOL=ON
+  CMAKE_OPTIONS += -DSPHINX_OUTPUT_MAN:BOOL=ON
 endif
-CONFIGURE_OPTIONS += --with-gcc-toolchain=$(USRDIR)/gcc/$(GCC_VERSION)
-CONFIGURE_OPTIONS += --with-optimize-option="$(OFLAG) $(GFLAG)"
+
+# Always build the libLLVM and libclang shared libraries
+CMAKE_OPTIONS += -DLLVM_BUILD_LLVM_DYLIB:BOOL=ON
+CMAKE_OPTIONS += -DLLVM_LINK_LLVM_DYLIB:BOOL=ON
+
+CMAKE_OPTIONS += -DCMAKE_VERBOSE_MAKEFILE:BOOL=ON
+
+CMAKE_OPTIONS += -DLLVM_COMPILER_IS_GCC_COMPATIBLE:BOOL=ON
 
-# Enable the cross-compiler in 3.8.X.
-CONFIGURE_OPTIONS.i386 += --enable-targets="x86"
-CONFIGURE_OPTIONS.sparc += --enable-targets="sparc"
+ifeq ($(CMAKE_NEEDS_SOLARIS_HOST),1)
+  CMAKE_OPTIONS += -DCMAKE_HOST_SOLARIS:BOOL=TRUE
+endif
+
+COMPONENT_BUILD_ENV = CC="$(CC)"
+COMPONENT_BUILD_ENV += CXX="$(CXX)"
+COMPONENT_BUILD_ENV += CFLAGS="$(CFLAGS)"
+COMPONENT_BUILD_ENV += CXXFLAGS="$(CXXFLAGS)"
+COMPONENT_BUILD_ENV += LDFLAGS="$(LDFLAGS)"
+COMPONENT_BUILD_ENV += LD_OPTIONS="$(LD_OPTIONS)"
+COMPONENT_BUILD_ENV += PATH="$(PATH)"
+COMPONENT_BUILD_ENV += LANG="C"
+COMPONENT_BUILD_ENV += LC_ALL="C"
+COMPONENT_BUILD_ENV += LD_EXEC_OPTIONS="-zaslr=disable"
 
 # Put this here for now until the gpatch problems are resolved.
-COMPONENT_BUILD_ARGS += -j8
+COMPONENT_BUILD_ARGS += -j4
 
 # use bash(1) to run the install recipes otherwise clang header installation
 # fails
 COMPONENT_INSTALL_ARGS += SHELL=/bin/bash
 
-# common targets
-# There are no master test results yet. TBDL in 3.8.X.
+COMPONENT_PRE_BUILD_ACTION += cd $(@D) ;
+COMPONENT_PRE_BUILD_ACTION += echo BITS: $(BITS) ;
+COMPONENT_PRE_BUILD_ACTION += echo Running cmake with $(CMAKE_OPTIONS) ;
+COMPONENT_PRE_BUILD_ACTION += /usr/bin/env - $(COMPONENT_BUILD_ENV) \
+			      $(CMAKE) $(CMAKE_OPTIONS) \
+			      $(COMPONENT_DIR)/$(COMPONENT_SRC) ;
+
+
+# There are no master test results just yet. But there will be
+# very soon.
 test:
-	@echo "Tests not yet implemented (wait for 3.8.X)."
+	@echo "Tests not yet implemented - coming soon in LLVM 3.8.1."
+
+system-test:    $(SYSTEM_TESTS_NOT_IMPLEMENTED)
 
 REQUIRED_PACKAGES += developer/gcc-4/gcc-common-49
 REQUIRED_PACKAGES += developer/gnu-binutils
@@ -309,6 +514,13 @@
 REQUIRED_PACKAGES += library/libffi
 REQUIRED_PACKAGES += library/libxml2
 REQUIRED_PACKAGES += library/zlib
+REQUIRED_PACKAGES += runtime/perl-522
+REQUIRED_PACKAGES += library/perl-5/xml-libxml
+REQUIRED_PACKAGES += library/perl-5/xml-namespacesupport
+REQUIRED_PACKAGES += library/perl-5/xml-parser
+REQUIRED_PACKAGES += library/perl-5/xml-sax
+REQUIRED_PACKAGES += library/perl-5/xml-sax-base
+REQUIRED_PACKAGES += library/perl-5/xml-simple
 REQUIRED_PACKAGES += runtime/python-27
 REQUIRED_PACKAGES += system/core-os
 REQUIRED_PACKAGES += system/header
@@ -318,3 +530,4 @@
 REQUIRED_PACKAGES += system/library/gcc/gcc-gobjc-runtime-49
 REQUIRED_PACKAGES += system/library/math
 REQUIRED_PACKAGES += system/linker
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/Solaris/man1/FileCheck.1	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,555 @@
+.\" Man page generated from reStructuredText.
+.
+.TH "FILECHECK" "1" "2016-07-10" "3.8" "LLVM"
+.SH NAME
+FileCheck \- Flexible pattern matching file verifier
+.
+.nr rst2man-indent-level 0
+.
+.de1 rstReportMargin
+\\$1 \\n[an-margin]
+level \\n[rst2man-indent-level]
+level margin: \\n[rst2man-indent\\n[rst2man-indent-level]]
+-
+\\n[rst2man-indent0]
+\\n[rst2man-indent1]
+\\n[rst2man-indent2]
+..
+.de1 INDENT
+.\" .rstReportMargin pre:
+. RS \\$1
+. nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin]
+. nr rst2man-indent-level +1
+.\" .rstReportMargin post:
+..
+.de UNINDENT
+. RE
+.\" indent \\n[an-margin]
+.\" old: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.nr rst2man-indent-level -1
+.\" new: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.in \\n[rst2man-indent\\n[rst2man-indent-level]]u
+..
+.SH SYNOPSIS
+.sp
+\fBFileCheck\fP \fImatch\-filename\fP [\fI\-\-check\-prefix=XXX\fP] [\fI\-\-strict\-whitespace\fP]
+.SH DESCRIPTION
+.sp
+\fBFileCheck\fP 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. \fBllc\fP) contains the expected information
+(for example, a movsd from esp or whatever is interesting).  This is similar to
+using \fBgrep\fP, but it is optimized for matching multiple different
+inputs in one file in a specific order.
+.sp
+The \fBmatch\-filename\fP file specifies the file that contains the patterns to
+match.  The file to verify is read from standard input unless the
+\fI\%\-\-input\-file\fP option is used.
+.SH OPTIONS
+.INDENT 0.0
+.TP
+.B \-help
+Print a summary of command line options.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-\-check\-prefix prefix
+FileCheck searches the contents of \fBmatch\-filename\fP for patterns to
+match.  By default, these patterns are prefixed with "\fBCHECK:\fP".
+If you\(aqd like to use a different prefix (e.g. because the same input
+file is checking multiple different tool or options), the
+\fI\%\-\-check\-prefix\fP argument allows you to specify one or more
+prefixes to match. Multiple prefixes are useful for tests which might
+change for different run options, but most lines remain the same.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-\-input\-file filename
+File to check (defaults to stdin).
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-\-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 \fI\%\-\-strict\-whitespace\fP argument disables this behavior. End\-of\-line
+sequences are canonicalized to UNIX\-style \fB\en\fP in all modes.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-\-implicit\-check\-not check\-pattern
+Adds implicit negative checks for the specified patterns between positive
+checks. The option allows writing stricter tests without stuffing them with
+\fBCHECK\-NOT\fPs.
+.sp
+For example, "\fB\-\-implicit\-check\-not warning:\fP" can be useful when testing
+diagnostic messages from tools that don\(aqt have an option similar to \fBclang
+\-verify\fP\&. With this option FileCheck will verify that input does not contain
+warnings not covered by any \fBCHECK:\fP patterns.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-version
+Show the version number of this program.
+.UNINDENT
+.SH EXIT STATUS
+.sp
+If \fBFileCheck\fP 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.
+.SH TUTORIAL
+.sp
+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:
+.INDENT 0.0
+.INDENT 3.5
+.sp
+.nf
+.ft C
+; RUN: llvm\-as < %s | llc \-march=x86\-64 | FileCheck %s
+.ft P
+.fi
+.UNINDENT
+.UNINDENT
+.sp
+This syntax says to pipe the current file ("\fB%s\fP") into \fBllvm\-as\fP, pipe
+that into \fBllc\fP, then pipe the output of \fBllc\fP into \fBFileCheck\fP\&.  This
+means that FileCheck will be verifying its standard input (the llc output)
+against the filename argument specified (the original \fB\&.ll\fP file specified by
+"\fB%s\fP").  To see how this works, let\(aqs look at the rest of the \fB\&.ll\fP file
+(after the RUN line):
+.INDENT 0.0
+.INDENT 3.5
+.sp
+.nf
+.ft C
+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
+}
+.ft P
+.fi
+.UNINDENT
+.UNINDENT
+.sp
+Here you can see some "\fBCHECK:\fP" lines specified in comments.  Now you can
+see how the file is piped into \fBllvm\-as\fP, then \fBllc\fP, and the machine code
+output is what we are verifying.  FileCheck checks the machine code output to
+verify that it matches what the "\fBCHECK:\fP" lines specify.
+.sp
+The syntax of the "\fBCHECK:\fP" 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 "\fBCHECK:\fP" line is required to match some thing in the test file exactly.
+.sp
+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 "\fBsub1:\fP" and "\fBinc4:\fP" labels, it will not match
+unless there is a "\fBsubl\fP" in between those labels.  If it existed somewhere
+else in the file, that would not count: "\fBgrep subl\fP" matches if "\fBsubl\fP"
+exists anywhere in the file.
+.SS The FileCheck \-check\-prefix option
+.sp
+The FileCheck \fB\-check\-prefix\fP option allows multiple test
+configurations to be driven from one \fI\&.ll\fP file.  This is useful in many
+circumstances, for example, testing different architectural variants with
+\fBllc\fP\&.  Here\(aqs a simple example:
+.INDENT 0.0
+.INDENT 3.5
+.sp
+.nf
+.ft C
+; RUN: llvm\-as < %s | llc \-mtriple=i686\-apple\-darwin9 \-mattr=sse41 \e
+; RUN:              | FileCheck %s \-check\-prefix=X32
+; RUN: llvm\-as < %s | llc \-mtriple=x86_64\-apple\-darwin9 \-mattr=sse41 \e
+; 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
+}
+.ft P
+.fi
+.UNINDENT
+.UNINDENT
+.sp
+In this case, we\(aqre testing that we get the expected code generation with
+both 32\-bit and 64\-bit code generation.
+.SS The "CHECK\-NEXT:" directive
+.sp
+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 "\fBCHECK:\fP" and "\fBCHECK\-NEXT:\fP" directives to specify
+this.  If you specified a custom check prefix, just use "\fB<PREFIX>\-NEXT:\fP".
+For example, something like this works as you\(aqd expect:
+.INDENT 0.0
+.INDENT 3.5
+.sp
+.nf
+.ft C
+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
+}
+.ft P
+.fi
+.UNINDENT
+.UNINDENT
+.sp
+"\fBCHECK\-NEXT:\fP" directives reject the input unless there is exactly one
+newline between it and the previous directive.  A "\fBCHECK\-NEXT:\fP" cannot be
+the first directive in a file.
+.SS The "CHECK\-SAME:" directive
+.sp
+Sometimes you want to match lines and would like to verify that matches happen
+on the same line as the previous match.  In this case, you can use "\fBCHECK:\fP"
+and "\fBCHECK\-SAME:\fP" directives to specify this.  If you specified a custom
+check prefix, just use "\fB<PREFIX>\-SAME:\fP".
+.sp
+"\fBCHECK\-SAME:\fP" is particularly powerful in conjunction with "\fBCHECK\-NOT:\fP"
+(described below).
+.sp
+For example, the following works like you\(aqd expect:
+.INDENT 0.0
+.INDENT 3.5
+.sp
+.nf
+.ft C
+!0 = !DILocation(line: 5, scope: !1, inlinedAt: !2)
+
+; CHECK:       !DILocation(line: 5,
+; CHECK\-NOT:               column:
+; CHECK\-SAME:              scope: ![[SCOPE:[0\-9]+]]
+.ft P
+.fi
+.UNINDENT
+.UNINDENT
+.sp
+"\fBCHECK\-SAME:\fP" directives reject the input if there are any newlines between
+it and the previous directive.  A "\fBCHECK\-SAME:\fP" cannot be the first
+directive in a file.
+.SS The "CHECK\-NOT:" directive
+.sp
+The "\fBCHECK\-NOT:\fP" directive is used to verify that a string doesn\(aqt 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:
+.INDENT 0.0
+.INDENT 3.5
+.sp
+.nf
+.ft C
+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
+}
+.ft P
+.fi
+.UNINDENT
+.UNINDENT
+.SS The "CHECK\-DAG:" directive
+.sp
+If it\(aqs necessary to match strings that don\(aqt occur in a strictly sequential
+order, "\fBCHECK\-DAG:\fP" could be used to verify them between two matches (or
+before the first match, or after the last match). For example, clang emits
+vtable globals in reverse order. Using \fBCHECK\-DAG:\fP, we can keep the checks
+in the natural order:
+.INDENT 0.0
+.INDENT 3.5
+.sp
+.nf
+.ft C
+// RUN: %clang_cc1 %s \-emit\-llvm \-o \- | FileCheck %s
+
+struct Foo { virtual void method(); };
+Foo f;  // emit vtable
+// CHECK\-DAG: @_ZTV3Foo =
+
+struct Bar { virtual void method(); };
+Bar b;
+// CHECK\-DAG: @_ZTV3Bar =
+.ft P
+.fi
+.UNINDENT
+.UNINDENT
+.sp
+\fBCHECK\-NOT:\fP directives could be mixed with \fBCHECK\-DAG:\fP directives to
+exclude strings between the surrounding \fBCHECK\-DAG:\fP directives. As a result,
+the surrounding \fBCHECK\-DAG:\fP directives cannot be reordered, i.e. all
+occurrences matching \fBCHECK\-DAG:\fP before \fBCHECK\-NOT:\fP must not fall behind
+occurrences matching \fBCHECK\-DAG:\fP after \fBCHECK\-NOT:\fP\&. For example,
+.INDENT 0.0
+.INDENT 3.5
+.sp
+.nf
+.ft C
+; CHECK\-DAG: BEFORE
+; CHECK\-NOT: NOT
+; CHECK\-DAG: AFTER
+.ft P
+.fi
+.UNINDENT
+.UNINDENT
+.sp
+This case will reject input strings where \fBBEFORE\fP occurs after \fBAFTER\fP\&.
+.sp
+With captured variables, \fBCHECK\-DAG:\fP is able to match valid topological
+orderings of a DAG with edges from the definition of a variable to its use.
+It\(aqs useful, e.g., when your test cases need to match different output
+sequences from the instruction scheduler. For example,
+.INDENT 0.0
+.INDENT 3.5
+.sp
+.nf
+.ft C
+; CHECK\-DAG: add [[REG1:r[0\-9]+]], r1, r2
+; CHECK\-DAG: add [[REG2:r[0\-9]+]], r3, r4
+; CHECK:     mul r5, [[REG1]], [[REG2]]
+.ft P
+.fi
+.UNINDENT
+.UNINDENT
+.sp
+In this case, any order of that two \fBadd\fP instructions will be allowed.
+.sp
+If you are defining \fIand\fP using variables in the same \fBCHECK\-DAG:\fP block,
+be aware that the definition rule can match \fIafter\fP its use.
+.sp
+So, for instance, the code below will pass:
+.INDENT 0.0
+.INDENT 3.5
+.sp
+.nf
+.ft C
+; CHECK\-DAG: vmov.32 [[REG2:d[0\-9]+]][0]
+; CHECK\-DAG: vmov.32 [[REG2]][1]
+vmov.32 d0[1]
+vmov.32 d0[0]
+.ft P
+.fi
+.UNINDENT
+.UNINDENT
+.sp
+While this other code, will not:
+.INDENT 0.0
+.INDENT 3.5
+.sp
+.nf
+.ft C
+; CHECK\-DAG: vmov.32 [[REG2:d[0\-9]+]][0]
+; CHECK\-DAG: vmov.32 [[REG2]][1]
+vmov.32 d1[1]
+vmov.32 d0[0]
+.ft P
+.fi
+.UNINDENT
+.UNINDENT
+.sp
+While this can be very useful, it\(aqs also dangerous, because in the case of
+register sequence, you must have a strong order (read before write, copy before
+use, etc). If the definition your test is looking for doesn\(aqt match (because
+of a bug in the compiler), it may match further away from the use, and mask
+real bugs away.
+.sp
+In those cases, to enforce the order, use a non\-DAG directive between DAG\-blocks.
+.SS The "CHECK\-LABEL:" directive
+.sp
+Sometimes in a file containing multiple tests divided into logical blocks, one
+or more \fBCHECK:\fP directives may inadvertently succeed by matching lines in a
+later block. While an error will usually eventually be generated, the check
+flagged as causing the error may not actually bear any relationship to the
+actual source of the problem.
+.sp
+In order to produce better error messages in these cases, the "\fBCHECK\-LABEL:\fP"
+directive can be used. It is treated identically to a normal \fBCHECK\fP
+directive except that FileCheck makes an additional assumption that a line
+matched by the directive cannot also be matched by any other check present in
+\fBmatch\-filename\fP; this is intended to be used for lines containing labels or
+other unique identifiers. Conceptually, the presence of \fBCHECK\-LABEL\fP divides
+the input stream into separate blocks, each of which is processed independently,
+preventing a \fBCHECK:\fP directive in one block matching a line in another block.
+For example,
+.INDENT 0.0
+.INDENT 3.5
+.sp
+.nf
+.ft C
+define %struct.C* @C_ctor_base(%struct.C* %this, i32 %x) {
+entry:
+; CHECK\-LABEL: C_ctor_base:
+; CHECK: mov [[SAVETHIS:r[0\-9]+]], r0
+; CHECK: bl A_ctor_base
+; CHECK: mov r0, [[SAVETHIS]]
+  %0 = bitcast %struct.C* %this to %struct.A*
+  %call = tail call %struct.A* @A_ctor_base(%struct.A* %0)
+  %1 = bitcast %struct.C* %this to %struct.B*
+  %call2 = tail call %struct.B* @B_ctor_base(%struct.B* %1, i32 %x)
+  ret %struct.C* %this
+}
+
+define %struct.D* @D_ctor_base(%struct.D* %this, i32 %x) {
+entry:
+; CHECK\-LABEL: D_ctor_base:
+.ft P
+.fi
+.UNINDENT
+.UNINDENT
+.sp
+The use of \fBCHECK\-LABEL:\fP directives in this case ensures that the three
+\fBCHECK:\fP directives only accept lines corresponding to the body of the
+\fB@C_ctor_base\fP function, even if the patterns match lines found later in
+the file. Furthermore, if one of these three \fBCHECK:\fP directives fail,
+FileCheck will recover by continuing to the next block, allowing multiple test
+failures to be detected in a single invocation.
+.sp
+There is no requirement that \fBCHECK\-LABEL:\fP directives contain strings that
+correspond to actual syntactic labels in a source or output language: they must
+simply uniquely match a single line in the file being verified.
+.sp
+\fBCHECK\-LABEL:\fP directives cannot contain variable definitions or uses.
+.SS FileCheck Pattern Matching Syntax
+.sp
+All FileCheck directives 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: \fB{{yourregex}}\fP\&.  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:
+.INDENT 0.0
+.INDENT 3.5
+.sp
+.nf
+.ft C
+; CHECK: movhpd      {{[0\-9]+}}(%esp), {{%xmm[0\-7]}}
+.ft P
+.fi
+.UNINDENT
+.UNINDENT
+.sp
+In this case, any offset from the ESP register will be allowed, and any xmm
+register will be allowed.
+.sp
+Because regular expressions are enclosed with double braces, they are
+visually distinct, and you don\(aqt 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
+\fB{{[{][{]}}\fP as your pattern.
+.SS FileCheck Variables
+.sp
+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,
+\fBFileCheck\fP allows named variables to be defined and substituted into
+patterns.  Here is a simple example:
+.INDENT 0.0
+.INDENT 3.5
+.sp
+.nf
+.ft C
+; CHECK: test5:
+; CHECK:    notw     [[REGISTER:%[a\-z]+]]
+; CHECK:    andw     {{.*}}[[REGISTER]]
+.ft P
+.fi
+.UNINDENT
+.UNINDENT
+.sp
+The first check line matches a regex \fB%[a\-z]+\fP and captures it into the
+variable \fBREGISTER\fP\&.  The second line verifies that whatever is in
+\fBREGISTER\fP occurs later in the file after an "\fBandw\fP".  \fBFileCheck\fP
+variable references are always contained in \fB[[ ]]\fP pairs, and their names can
+be formed with the regex \fB[a\-zA\-Z][a\-zA\-Z0\-9]*\fP\&.  If a colon follows the name,
+then it is a definition of the variable; otherwise, it is a use.
+.sp
+\fBFileCheck\fP variables can be defined multiple times, and uses always
+get the latest value.  Variables can also be used later on the same line they
+were defined on. For example:
+.INDENT 0.0
+.INDENT 3.5
+.sp
+.nf
+.ft C
+; CHECK: op [[REG:r[0\-9]+]], [[REG]]
+.ft P
+.fi
+.UNINDENT
+.UNINDENT
+.sp
+Can be useful if you want the operands of \fBop\fP to be the same register,
+and don\(aqt care exactly which register it is.
+.SS FileCheck Expressions
+.sp
+Sometimes there\(aqs a need to verify output which refers line numbers of the
+match file, e.g. when testing compiler diagnostics.  This introduces a certain
+fragility of the match file structure, as "\fBCHECK:\fP" lines contain absolute
+line numbers in the same file, which have to be updated whenever line numbers
+change due to text addition or deletion.
+.sp
+To support this case, FileCheck allows using \fB[[@LINE]]\fP,
+\fB[[@LINE+<offset>]]\fP, \fB[[@LINE\-<offset>]]\fP expressions in patterns. These
+expressions expand to a number of the line where a pattern is located (with an
+optional integer offset).
+.sp
+This way match patterns can be put near the relevant test lines and include
+relative line number references, for example:
+.INDENT 0.0
+.INDENT 3.5
+.sp
+.nf
+.ft C
+// CHECK: test.cpp:[[@LINE+4]]:6: error: expected \(aq;\(aq after top level declarator
+// CHECK\-NEXT: {{^int a}}
+// CHECK\-NEXT: {{^     \e^}}
+// CHECK\-NEXT: {{^     ;}}
+int a
+.ft P
+.fi
+.UNINDENT
+.UNINDENT
+.SH AUTHOR
+Maintained by The LLVM Team (http://llvm.org/).
+.SH COPYRIGHT
+2003-2016, LLVM Project
+.\" Generated by docutils manpage writer.
+.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/Solaris/man1/bugpoint.1	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,292 @@
+.\" Man page generated from reStructuredText.
+.
+.TH "BUGPOINT" "1" "2016-07-10" "3.8" "LLVM"
+.SH NAME
+bugpoint \- automatic test case reduction tool
+.
+.nr rst2man-indent-level 0
+.
+.de1 rstReportMargin
+\\$1 \\n[an-margin]
+level \\n[rst2man-indent-level]
+level margin: \\n[rst2man-indent\\n[rst2man-indent-level]]
+-
+\\n[rst2man-indent0]
+\\n[rst2man-indent1]
+\\n[rst2man-indent2]
+..
+.de1 INDENT
+.\" .rstReportMargin pre:
+. RS \\$1
+. nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin]
+. nr rst2man-indent-level +1
+.\" .rstReportMargin post:
+..
+.de UNINDENT
+. RE
+.\" indent \\n[an-margin]
+.\" old: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.nr rst2man-indent-level -1
+.\" new: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.in \\n[rst2man-indent\\n[rst2man-indent-level]]u
+..
+.SH SYNOPSIS
+.sp
+\fBbugpoint\fP [\fIoptions\fP] [\fIinput LLVM ll/bc files\fP] [\fILLVM passes\fP] \fB\-\-args\fP
+\fIprogram arguments\fP
+.SH DESCRIPTION
+.sp
+\fBbugpoint\fP 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 \fBbugpoint\fP, as well as
+advice for using bugpoint, see \fIllvm/docs/Bugpoint.html\fP in the LLVM
+distribution.
+.SH OPTIONS
+.sp
+\fB\-\-additional\-so\fP \fIlibrary\fP
+.INDENT 0.0
+.INDENT 3.5
+Load the dynamic shared object \fIlibrary\fP 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.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-append\-exit\-code\fP=\fI{true,false}\fP
+.INDENT 0.0
+.INDENT 3.5
+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.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-args\fP \fIprogram args\fP
+.INDENT 0.0
+.INDENT 3.5
+Pass all arguments specified after \fB\-\-args\fP to the test program whenever it runs.
+Note that if any of the \fIprogram args\fP start with a "\fB\-\fP", you should use:
+.INDENT 0.0
+.INDENT 3.5
+.sp
+.nf
+.ft C
+bugpoint [bugpoint args] \-\-args \-\- [program args]
+.ft P
+.fi
+.UNINDENT
+.UNINDENT
+.sp
+The "\fB\-\-\fP" right after the \fB\-\-args\fP option tells \fBbugpoint\fP to consider
+any options starting with "\fB\-\fP" to be part of the \fB\-\-args\fP option, not as
+options to \fBbugpoint\fP itself.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-tool\-args\fP \fItool args\fP
+.INDENT 0.0
+.INDENT 3.5
+Pass all arguments specified after \fB\-\-tool\-args\fP to the LLVM tool under test
+(\fBllc\fP, \fBlli\fP, etc.) whenever it runs.  You should use this option in the
+following way:
+.INDENT 0.0
+.INDENT 3.5
+.sp
+.nf
+.ft C
+bugpoint [bugpoint args] \-\-tool\-args \-\- [tool args]
+.ft P
+.fi
+.UNINDENT
+.UNINDENT
+.sp
+The "\fB\-\-\fP" right after the \fB\-\-tool\-args\fP option tells \fBbugpoint\fP to
+consider any options starting with "\fB\-\fP" to be part of the \fB\-\-tool\-args\fP
+option, not as options to \fBbugpoint\fP itself. (See \fB\-\-args\fP, above.)
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-safe\-tool\-args\fP \fItool args\fP
+.INDENT 0.0
+.INDENT 3.5
+Pass all arguments specified after \fB\-\-safe\-tool\-args\fP to the "safe" execution
+tool.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-gcc\-tool\-args\fP \fIgcc tool args\fP
+.INDENT 0.0
+.INDENT 3.5
+Pass all arguments specified after \fB\-\-gcc\-tool\-args\fP to the invocation of
+\fBgcc\fP\&.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-opt\-args\fP \fIopt args\fP
+.INDENT 0.0
+.INDENT 3.5
+Pass all arguments specified after \fB\-\-opt\-args\fP to the invocation of \fBopt\fP\&.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-disable\-{dce,simplifycfg}\fP
+.INDENT 0.0
+.INDENT 3.5
+Do not run the specified passes to clean up and reduce the size of the test
+program. By default, \fBbugpoint\fP uses these passes internally when attempting to
+reduce test programs.  If you\(aqre trying to find a bug in one of these passes,
+\fBbugpoint\fP may crash.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-enable\-valgrind\fP
+.INDENT 0.0
+.INDENT 3.5
+Use valgrind to find faults in the optimization phase. This will allow
+bugpoint to find otherwise asymptomatic problems caused by memory
+mis\-management.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-find\-bugs\fP
+.INDENT 0.0
+.INDENT 3.5
+Continually randomize the specified passes and run them on the test program
+until a bug is found or the user kills \fBbugpoint\fP\&.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-help\fP
+.INDENT 0.0
+.INDENT 3.5
+Print a summary of command line options.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-input\fP \fIfilename\fP
+.INDENT 0.0
+.INDENT 3.5
+Open \fIfilename\fP and redirect the standard input of the test program, whenever
+it runs, to come from that file.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-load\fP \fIplugin\fP
+.INDENT 0.0
+.INDENT 3.5
+Load the dynamic object \fIplugin\fP into \fBbugpoint\fP 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 \fB\-help\fP and \fB\-\-load\fP options together; for example:
+.INDENT 0.0
+.INDENT 3.5
+.sp
+.nf
+.ft C
+bugpoint \-\-load myNewPass.so \-help
+.ft P
+.fi
+.UNINDENT
+.UNINDENT
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-mlimit\fP \fImegabytes\fP
+.INDENT 0.0
+.INDENT 3.5
+Specifies an upper limit on memory usage of the optimization and codegen. Set
+to zero to disable the limit.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-output\fP \fIfilename\fP
+.INDENT 0.0
+.INDENT 3.5
+Whenever the test program produces output on its standard output stream, it
+should match the contents of \fIfilename\fP (the "reference output"). If you
+do not use this option, \fBbugpoint\fP will attempt to generate a reference output
+by compiling the program with the "safe" backend and running it.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-run\-{int,jit,llc,custom}\fP
+.INDENT 0.0
+.INDENT 3.5
+Whenever the test program is compiled, \fBbugpoint\fP 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 \fB\-\-exec\-command\fP) respectively.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-safe\-{llc,custom}\fP
+.INDENT 0.0
+.INDENT 3.5
+When debugging a code generator, \fBbugpoint\fP 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 \fB\-\-exec\-command\fP)
+respectively. The interpreter and the JIT backends cannot currently
+be used as the "safe" backends.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-exec\-command\fP \fIcommand\fP
+.INDENT 0.0
+.INDENT 3.5
+This option defines the command to use with the \fB\-\-run\-custom\fP and
+\fB\-\-safe\-custom\fP options to execute the bitcode testcase. This can
+be useful for cross\-compilation.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-compile\-command\fP \fIcommand\fP
+.INDENT 0.0
+.INDENT 3.5
+This option defines the command to use with the \fB\-\-compile\-custom\fP
+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:
+.INDENT 0.0
+.INDENT 3.5
+.sp
+.nf
+.ft C
+#!/bin/sh
+llc "$@"
+not FileCheck [bugpoint input file].ll < bugpoint\-test\-program.s
+.ft P
+.fi
+.UNINDENT
+.UNINDENT
+.sp
+This script will "fail" as long as FileCheck passes. So the result
+will be the minimum bitcode that passes FileCheck.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-safe\-path\fP \fIpath\fP
+.INDENT 0.0
+.INDENT 3.5
+This option defines the path to the command to execute with the
+\fB\-\-safe\-{int,jit,llc,custom}\fP
+option.
+.UNINDENT
+.UNINDENT
+.SH EXIT STATUS
+.sp
+If \fBbugpoint\fP succeeds in finding a problem, it will exit with 0.  Otherwise,
+if an error occurs, it will exit with a non\-zero value.
+.SH SEE ALSO
+.sp
+opt|opt
+.SH AUTHOR
+Maintained by The LLVM Team (http://llvm.org/).
+.SH COPYRIGHT
+2003-2016, LLVM Project
+.\" Generated by docutils manpage writer.
+.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/Solaris/man1/clang.1	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,583 @@
+.\" Man page generated from reStructuredText.
+.
+.TH "CLANG" "1" "Jul 10, 2016" "3.8" "Clang"
+.SH NAME
+clang \- the Clang C, C++, and Objective-C compiler
+.
+.nr rst2man-indent-level 0
+.
+.de1 rstReportMargin
+\\$1 \\n[an-margin]
+level \\n[rst2man-indent-level]
+level margin: \\n[rst2man-indent\\n[rst2man-indent-level]]
+-
+\\n[rst2man-indent0]
+\\n[rst2man-indent1]
+\\n[rst2man-indent2]
+..
+.de1 INDENT
+.\" .rstReportMargin pre:
+. RS \\$1
+. nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin]
+. nr rst2man-indent-level +1
+.\" .rstReportMargin post:
+..
+.de UNINDENT
+. RE
+.\" indent \\n[an-margin]
+.\" old: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.nr rst2man-indent-level -1
+.\" new: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.in \\n[rst2man-indent\\n[rst2man-indent-level]]u
+..
+.SH SYNOPSIS
+.sp
+\fBclang\fP [\fIoptions\fP] \fIfilename ...\fP
+.SH DESCRIPTION
+.sp
+\fBclang\fP is a C, C++, and Objective\-C compiler which encompasses
+preprocessing, parsing, optimization, code generation, assembly, and linking.
+Depending on which high\-level mode setting is passed, Clang will stop before
+doing a full link.  While Clang is highly integrated, it is important to
+understand the stages of compilation, to understand how to invoke it.  These
+stages are:
+.INDENT 0.0
+.TP
+.B Driver
+The clang executable is actually a small driver which controls the overall
+execution of other tools such as the compiler, assembler and linker.
+Typically you do not need to interact with the driver, but you
+transparently use it to run the other tools.
+.TP
+.B Preprocessing
+This stage handles tokenization of the input source file, macro expansion,
+#include expansion and handling of other preprocessor directives.  The
+output of this stage is typically called a ".i" (for C), ".ii" (for C++),
+".mi" (for Objective\-C), or ".mii" (for Objective\-C++) file.
+.TP
+.B Parsing and Semantic Analysis
+This stage parses the input file, translating preprocessor tokens into a
+parse tree.  Once in the form of a parse tree, it applies semantic
+analysis to compute types for expressions as well and determine whether
+the code is well formed. This stage is responsible for generating most of
+the compiler warnings as well as parse errors. The output of this stage is
+an "Abstract Syntax Tree" (AST).
+.TP
+.B Code Generation and Optimization
+This stage translates an AST into low\-level intermediate code (known as
+"LLVM IR") and ultimately to machine code.  This phase is responsible for
+optimizing the generated code and handling target\-specific code generation.
+The output of this stage is typically called a ".s" file or "assembly" file.
+.sp
+Clang also supports the use of an integrated assembler, in which the code
+generator produces object files directly. This avoids the overhead of
+generating the ".s" file and of calling the target assembler.
+.TP
+.B Assembler
+This stage runs the target assembler to translate the output of the
+compiler into a target object file. The output of this stage is typically
+called a ".o" file or "object" file.
+.TP
+.B Linker
+This stage runs the target linker to merge multiple object files into an
+executable or dynamic library. The output of this stage is typically called
+an "a.out", ".dylib" or ".so" file.
+.UNINDENT
+.sp
+\fBClang Static Analyzer\fP
+.sp
+The Clang Static Analyzer is a tool that scans source code to try to find bugs
+through code analysis.  This tool uses many parts of Clang and is built into
+the same driver.  Please see <\fI\%http://clang\-analyzer.llvm.org\fP> for more details
+on how to use the static analyzer.
+.SH OPTIONS
+.SS Stage Selection Options
+.INDENT 0.0
+.TP
+.B \-E
+Run the preprocessor stage.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-fsyntax\-only
+Run the preprocessor, parser and type checking stages.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-S
+Run the previous stages as well as LLVM generation and optimization stages
+and target\-specific code generation, producing an assembly file.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-c
+Run all of the above, plus the assembler, generating a target ".o" object file.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B no stage selection option
+If no stage selection option is specified, all stages above are run, and the
+linker is run to combine the results into an executable or shared library.
+.UNINDENT
+.SS Language Selection and Mode Options
+.INDENT 0.0
+.TP
+.B \-x <language>
+Treat subsequent input files as having type language.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-std=<language>
+Specify the language standard to compile for.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-stdlib=<library>
+Specify the C++ standard library to use; supported options are libstdc++ and
+libc++.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-ansi
+Same as \-std=c89.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-ObjC, \-ObjC++
+Treat source input files as Objective\-C and Object\-C++ inputs respectively.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-trigraphs
+Enable trigraphs.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-ffreestanding
+Indicate that the file should be compiled for a freestanding, not a hosted,
+environment.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-fno\-builtin
+Disable special handling and optimizations of builtin functions like
+\fBstrlen()\fP and \fBmalloc()\fP\&.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-fmath\-errno
+Indicate that math functions should be treated as updating \fBerrno\fP\&.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-fpascal\-strings
+Enable support for Pascal\-style strings with "\epfoo".
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-fms\-extensions
+Enable support for Microsoft extensions.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-fmsc\-version=
+Set _MSC_VER. Defaults to 1300 on Windows. Not set otherwise.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-fborland\-extensions
+Enable support for Borland extensions.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-fwritable\-strings
+Make all string literals default to writable.  This disables uniquing of
+strings and other optimizations.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-flax\-vector\-conversions
+Allow loose type checking rules for implicit vector conversions.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-fblocks
+Enable the "Blocks" language feature.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-fobjc\-gc\-only
+Indicate that Objective\-C code should be compiled in GC\-only mode, which only
+works when Objective\-C Garbage Collection is enabled.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-fobjc\-gc
+Indicate that Objective\-C code should be compiled in hybrid\-GC mode, which
+works with both GC and non\-GC mode.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-fobjc\-abi\-version=version
+Select the Objective\-C ABI version to use. Available versions are 1 (legacy
+"fragile" ABI), 2 (non\-fragile ABI 1), and 3 (non\-fragile ABI 2).
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-fobjc\-nonfragile\-abi\-version=<version>
+Select the Objective\-C non\-fragile ABI version to use by default. This will
+only be used as the Objective\-C ABI when the non\-fragile ABI is enabled
+(either via \fI\%\-fobjc\-nonfragile\-abi\fP, or because it is the platform
+default).
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-fobjc\-nonfragile\-abi
+Enable use of the Objective\-C non\-fragile ABI. On platforms for which this is
+the default ABI, it can be disabled with \fB\-fno\-objc\-nonfragile\-abi\fP\&.
+.UNINDENT
+.SS Target Selection Options
+.sp
+Clang fully supports cross compilation as an inherent part of its design.
+Depending on how your version of Clang is configured, it may have support for a
+number of cross compilers, or may only support a native target.
+.INDENT 0.0
+.TP
+.B \-arch <architecture>
+Specify the architecture to build for.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-mmacosx\-version\-min=<version>
+When building for Mac OS X, specify the minimum version supported by your
+application.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-miphoneos\-version\-min
+When building for iPhone OS, specify the minimum version supported by your
+application.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-march=<cpu>
+Specify that Clang should generate code for a specific processor family
+member and later.  For example, if you specify \-march=i486, the compiler is
+allowed to generate instructions that are valid on i486 and later processors,
+but which may not exist on earlier ones.
+.UNINDENT
+.SS Code Generation Options
+.INDENT 0.0
+.TP
+.B \-O0, \-O1, \-O2, \-O3, \-Ofast, \-Os, \-Oz, \-O, \-O4
+Specify which optimization level to use:
+.INDENT 7.0
+.INDENT 3.5
+\fI\%\-O0\fP Means "no optimization": this level compiles the fastest and
+generates the most debuggable code.
+.sp
+\fI\%\-O1\fP Somewhere between \fI\%\-O0\fP and \fI\%\-O2\fP\&.
+.sp
+\fI\%\-O2\fP Moderate level of optimization which enables most
+optimizations.
+.sp
+\fI\%\-O3\fP Like \fI\%\-O2\fP, except that it enables optimizations that
+take longer to perform or that may generate larger code (in an attempt to
+make the program run faster).
+.sp
+\fI\%\-Ofast\fP Enables all the optimizations from \fI\%\-O3\fP along
+with other aggressive optimizations that may violate strict compliance with
+language standards.
+.sp
+\fI\%\-Os\fP Like \fI\%\-O2\fP with extra optimizations to reduce code
+size.
+.sp
+\fI\%\-Oz\fP Like \fI\%\-Os\fP (and thus \fI\%\-O2\fP), but reduces code
+size further.
+.sp
+\fI\%\-O\fP Equivalent to \fI\%\-O2\fP\&.
+.sp
+\fI\%\-O4\fP and higher
+.INDENT 0.0
+.INDENT 3.5
+Currently equivalent to \fI\%\-O3\fP
+.UNINDENT
+.UNINDENT
+.UNINDENT
+.UNINDENT
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-g
+Generate debug information.  Note that Clang debug information works best at \-O0.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-gmodules
+Generate debug information that contains external references to
+types defined in clang modules or precompiled headers instead of
+emitting redundant debug type information into every object file.
+This option implies \fB\-fmodule\-format=obj\fP\&.
+.sp
+This option should not be used when building static libraries for
+distribution to other machines because the debug info will contain
+references to the module cache on the machine the object files in
+the library were built on.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-fstandalone\-debug \-fno\-standalone\-debug
+Clang supports a number of optimizations to reduce the size of debug
+information in the binary. They work based on the assumption that the
+debug type information can be spread out over multiple compilation units.
+For instance, Clang will not emit type definitions for types that are not
+needed by a module and could be replaced with a forward declaration.
+Further, Clang will only emit type info for a dynamic C++ class in the
+module that contains the vtable for the class.
+.sp
+The \fB\-fstandalone\-debug\fP option turns off these optimizations.
+This is useful when working with 3rd\-party libraries that don\(aqt come with
+debug information.  This is the default on Darwin.  Note that Clang will
+never emit type information for types that are not referenced at all by the
+program.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-fexceptions
+Enable generation of unwind information. This allows exceptions to be thrown
+through Clang compiled stack frames.  This is on by default in x86\-64.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-ftrapv
+Generate code to catch integer overflow errors.  Signed integer overflow is
+undefined in C. With this flag, extra code is generated to detect this and
+abort when it happens.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-fvisibility
+This flag sets the default visibility level.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-fcommon
+This flag specifies that variables without initializers get common linkage.
+It can be disabled with \fB\-fno\-common\fP\&.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-ftls\-model=<model>
+Set the default thread\-local storage (TLS) model to use for thread\-local
+variables. Valid values are: "global\-dynamic", "local\-dynamic",
+"initial\-exec" and "local\-exec". The default is "global\-dynamic". The default
+model can be overridden with the tls_model attribute. The compiler will try
+to choose a more efficient model if possible.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-flto, \-emit\-llvm
+Generate output files in LLVM formats, suitable for link time optimization.
+When used with \fI\%\-S\fP this generates LLVM intermediate language
+assembly files, otherwise this generates LLVM bitcode format object files
+(which may be passed to the linker depending on the stage selection options).
+.UNINDENT
+.SS Driver Options
+.INDENT 0.0
+.TP
+.B \-###
+Print (but do not run) the commands to run for this compilation.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-\-help
+Display available options.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-Qunused\-arguments
+Do not emit any warnings for unused driver arguments.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-Wa,<args>
+Pass the comma separated arguments in args to the assembler.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-Wl,<args>
+Pass the comma separated arguments in args to the linker.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-Wp,<args>
+Pass the comma separated arguments in args to the preprocessor.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-Xanalyzer <arg>
+Pass arg to the static analyzer.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-Xassembler <arg>
+Pass arg to the assembler.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-Xlinker <arg>
+Pass arg to the linker.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-Xpreprocessor <arg>
+Pass arg to the preprocessor.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-o <file>
+Write output to file.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-print\-file\-name=<file>
+Print the full library path of file.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-print\-libgcc\-file\-name
+Print the library path for "libgcc.a".
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-print\-prog\-name=<name>
+Print the full program path of name.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-print\-search\-dirs
+Print the paths used for finding libraries and programs.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-save\-temps
+Save intermediate compilation results.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-integrated\-as, \-no\-integrated\-as
+Used to enable and disable, respectively, the use of the integrated
+assembler. Whether the integrated assembler is on by default is target
+dependent.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-time
+Time individual commands.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-ftime\-report
+Print timing summary of each stage of compilation.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-v
+Show commands to run and use verbose output.
+.UNINDENT
+.SS Diagnostics Options
+.INDENT 0.0
+.TP
+.B \-fshow\-column, \-fshow\-source\-location, \-fcaret\-diagnostics, \-fdiagnostics\-fixit\-info, \-fdiagnostics\-parseable\-fixits, \-fdiagnostics\-print\-source\-range\-info, \-fprint\-source\-range\-info, \-fdiagnostics\-show\-option, \-fmessage\-length
+These options control how Clang prints out information about diagnostics
+(errors and warnings). Please see the Clang User\(aqs Manual for more information.
+.UNINDENT
+.SS Preprocessor Options
+.INDENT 0.0
+.TP
+.B \-D<macroname>=<value>
+Adds an implicit #define into the predefines buffer which is read before the
+source file is preprocessed.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-U<macroname>
+Adds an implicit #undef into the predefines buffer which is read before the
+source file is preprocessed.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-include <filename>
+Adds an implicit #include into the predefines buffer which is read before the
+source file is preprocessed.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-I<directory>
+Add the specified directory to the search path for include files.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-F<directory>
+Add the specified directory to the search path for framework include files.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-nostdinc
+Do not search the standard system directories or compiler builtin directories
+for include files.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-nostdlibinc
+Do not search the standard system directories for include files, but do
+search compiler builtin include directories.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-nobuiltininc
+Do not search clang\(aqs builtin directory for include files.
+.UNINDENT
+.SH ENVIRONMENT
+.INDENT 0.0
+.TP
+.B TMPDIR, TEMP, TMP
+These environment variables are checked, in order, for the location to write
+temporary files used during the compilation process.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B CPATH
+If this environment variable is present, it is treated as a delimited list of
+paths to be added to the default system include path list. The delimiter is
+the platform dependent delimiter, as used in the PATH environment variable.
+.sp
+Empty components in the environment variable are ignored.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B C_INCLUDE_PATH, OBJC_INCLUDE_PATH, CPLUS_INCLUDE_PATH, OBJCPLUS_INCLUDE_PATH
+These environment variables specify additional paths, as for \fI\%CPATH\fP, which are
+only used when processing the appropriate language.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B MACOSX_DEPLOYMENT_TARGET
+If \fI\%\-mmacosx\-version\-min\fP is unspecified, the default deployment
+target is read from this environment variable. This option only affects
+Darwin targets.
+.UNINDENT
+.SH BUGS
+.sp
+To report bugs, please visit <\fI\%http://llvm.org/bugs/\fP>.  Most bug reports should
+include preprocessed source files (use the \fI\%\-E\fP option) and the full
+output of the compiler, along with information to reproduce.
+.SH SEE ALSO
+.sp
+\fBas(1)\fP, \fBld(1)\fP
+.SH AUTHOR
+Maintained by the Clang / LLVM Team (<http://clang.llvm.org>)
+.SH COPYRIGHT
+2007-2016, The Clang Team
+.\" Generated by docutils manpage writer.
+.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/Solaris/man1/lit.1	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,471 @@
+.\" Man page generated from reStructuredText.
+.
+.TH "LIT" "1" "2016-07-10" "3.8" "LLVM"
+.SH NAME
+lit \- LLVM Integrated Tester
+.
+.nr rst2man-indent-level 0
+.
+.de1 rstReportMargin
+\\$1 \\n[an-margin]
+level \\n[rst2man-indent-level]
+level margin: \\n[rst2man-indent\\n[rst2man-indent-level]]
+-
+\\n[rst2man-indent0]
+\\n[rst2man-indent1]
+\\n[rst2man-indent2]
+..
+.de1 INDENT
+.\" .rstReportMargin pre:
+. RS \\$1
+. nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin]
+. nr rst2man-indent-level +1
+.\" .rstReportMargin post:
+..
+.de UNINDENT
+. RE
+.\" indent \\n[an-margin]
+.\" old: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.nr rst2man-indent-level -1
+.\" new: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.in \\n[rst2man-indent\\n[rst2man-indent-level]]u
+..
+.SH SYNOPSIS
+.sp
+\fBlit\fP [\fIoptions\fP] [\fItests\fP]
+.SH DESCRIPTION
+.sp
+\fBlit\fP is a portable tool for executing LLVM and Clang style test
+suites, summarizing their results, and providing indication of failures.
+\fBlit\fP is designed to be a lightweight testing tool with as simple a
+user interface as possible.
+.sp
+\fBlit\fP should be run with one or more \fItests\fP to run specified on the
+command line.  Tests can be either individual test files or directories to
+search for tests (see \fI\%TEST DISCOVERY\fP).
+.sp
+Each specified test will be executed (potentially in parallel) and once all
+tests have been run \fBlit\fP will print summary information on the number
+of tests which passed or failed (see \fI\%TEST STATUS RESULTS\fP).  The
+\fBlit\fP program will execute with a non\-zero exit code if any tests
+fail.
+.sp
+By default \fBlit\fP will use a succinct progress display and will only
+print summary information for test failures.  See \fI\%OUTPUT OPTIONS\fP for
+options controlling the \fBlit\fP progress display and output.
+.sp
+\fBlit\fP also includes a number of options for controlling how tests are
+executed (specific features may depend on the particular test format).  See
+\fI\%EXECUTION OPTIONS\fP for more information.
+.sp
+Finally, \fBlit\fP also supports additional options for only running a
+subset of the options specified on the command line, see
+\fI\%SELECTION OPTIONS\fP for more information.
+.sp
+Users interested in the \fBlit\fP architecture or designing a
+\fBlit\fP testing implementation should see \fI\%LIT INFRASTRUCTURE\fP\&.
+.SH GENERAL OPTIONS
+.INDENT 0.0
+.TP
+.B \-h, \-\-help
+Show the \fBlit\fP help message.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-j N, \-\-threads=N
+Run \fBN\fP tests in parallel.  By default, this is automatically chosen to
+match the number of detected available CPUs.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-\-config\-prefix=NAME
+Search for \fB\fINAME\fP\fP\fB\&.cfg\fP and \fB\fINAME\fP\fP\fB\&.site.cfg\fP when searching for
+test suites, instead of \fBlit.cfg\fP and \fBlit.site.cfg\fP\&.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-D NAME, \-D NAME=VALUE, \-\-param NAME, \-\-param NAME=VALUE
+Add a user defined parameter \fBNAME\fP with the given \fBVALUE\fP (or the empty
+string if not given).  The meaning and use of these parameters is test suite
+dependent.
+.UNINDENT
+.SH OUTPUT OPTIONS
+.INDENT 0.0
+.TP
+.B \-q, \-\-quiet
+Suppress any output except for test failures.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-s, \-\-succinct
+Show less output, for example don\(aqt show information on tests that pass.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-v, \-\-verbose
+Show more information on test failures, for example the entire test output
+instead of just the test result.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-a, \-\-show\-all
+Show more information about all tests, for example the entire test
+commandline and output.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-\-no\-progress\-bar
+Do not use curses based progress bar.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-\-show\-unsupported
+Show the names of unsupported tests.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-\-show\-xfail
+Show the names of tests that were expected to fail.
+.UNINDENT
+.SH EXECUTION OPTIONS
+.INDENT 0.0
+.TP
+.B \-\-path=PATH
+Specify an additional \fBPATH\fP to use when searching for executables in tests.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-\-vg
+Run individual tests under valgrind (using the memcheck tool).  The
+\fB\-\-error\-exitcode\fP argument for valgrind is used so that valgrind failures
+will cause the program to exit with a non\-zero status.
+.sp
+When this option is enabled, \fBlit\fP will also automatically provide a
+"\fBvalgrind\fP" feature that can be used to conditionally disable (or expect
+failure in) certain tests.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-\-vg\-arg=ARG
+When \fI\%\-\-vg\fP is used, specify an additional argument to pass to
+\fBvalgrind\fP itself.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-\-vg\-leak
+When \fI\%\-\-vg\fP is used, enable memory leak checks.  When this option is
+enabled, \fBlit\fP will also automatically provide a "\fBvg_leak\fP"
+feature that can be used to conditionally disable (or expect failure in)
+certain tests.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-\-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 \fB\-j 1\fP\&.
+.UNINDENT
+.SH SELECTION OPTIONS
+.INDENT 0.0
+.TP
+.B \-\-max\-tests=N
+Run at most \fBN\fP tests and then terminate.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-\-max\-time=N
+Spend at most \fBN\fP seconds (approximately) running tests and then terminate.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-\-shuffle
+Run the tests in a random order.
+.UNINDENT
+.SH ADDITIONAL OPTIONS
+.INDENT 0.0
+.TP
+.B \-\-debug
+Run \fBlit\fP in debug mode, for debugging configuration issues and
+\fBlit\fP itself.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-\-show\-suites
+List the discovered test suites and exit.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-\-show\-tests
+List all of the discovered tests and exit.
+.UNINDENT
+.SH EXIT STATUS
+.sp
+\fBlit\fP 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).
+.SH TEST DISCOVERY
+.sp
+The inputs passed to \fBlit\fP can be either individual tests, or entire
+directories or hierarchies of tests to run.  When \fBlit\fP starts up, the
+first thing it does is convert the inputs into a complete list of tests to run
+as part of \fItest discovery\fP\&.
+.sp
+In the \fBlit\fP model, every test must exist inside some \fItest suite\fP\&.
+\fBlit\fP resolves the inputs specified on the command line to test suites
+by searching upwards from the input path until it finds a \fBlit.cfg\fP or
+\fBlit.site.cfg\fP file.  These files serve as both a marker of test suites
+and as configuration files which \fBlit\fP loads in order to understand
+how to find and run the tests inside the test suite.
+.sp
+Once \fBlit\fP 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.
+.sp
+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, \fBlit\fP always identifies tests by the test
+suite they are in, and their relative path inside the test suite.  For
+appropriately configured projects, this allows \fBlit\fP to provide
+convenient and flexible support for out\-of\-tree builds.
+.SH TEST STATUS RESULTS
+.sp
+Each test ultimately produces one of the following six results:
+.sp
+\fBPASS\fP
+.INDENT 0.0
+.INDENT 3.5
+The test succeeded.
+.UNINDENT
+.UNINDENT
+.sp
+\fBXFAIL\fP
+.INDENT 0.0
+.INDENT 3.5
+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.
+.UNINDENT
+.UNINDENT
+.sp
+\fBXPASS\fP
+.INDENT 0.0
+.INDENT 3.5
+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).
+.UNINDENT
+.UNINDENT
+.sp
+\fBFAIL\fP
+.INDENT 0.0
+.INDENT 3.5
+The test failed.
+.UNINDENT
+.UNINDENT
+.sp
+\fBUNRESOLVED\fP
+.INDENT 0.0
+.INDENT 3.5
+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.
+.UNINDENT
+.UNINDENT
+.sp
+\fBUNSUPPORTED\fP
+.INDENT 0.0
+.INDENT 3.5
+The test is not supported in this environment.  This is used by test formats
+which can report unsupported tests.
+.UNINDENT
+.UNINDENT
+.sp
+Depending on the test format tests may produce additional information about
+their status (generally only for failures).  See the \fI\%OUTPUT OPTIONS\fP
+section for more information.
+.SH LIT INFRASTRUCTURE
+.sp
+This section describes the \fBlit\fP testing architecture for users interested in
+creating a new \fBlit\fP testing implementation, or extending an existing one.
+.sp
+\fBlit\fP proper is primarily an infrastructure for discovering and running
+arbitrary tests, and to expose a single convenient interface to these
+tests. \fBlit\fP itself doesn\(aqt know how to run tests, rather this logic is
+defined by \fItest suites\fP\&.
+.SS TEST SUITES
+.sp
+As described in \fI\%TEST DISCOVERY\fP, tests are always located inside a \fItest
+suite\fP\&.  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.
+.sp
+\fBlit\fP identifies test suites as directories containing \fBlit.cfg\fP or
+\fBlit.site.cfg\fP files (see also \fI\%\-\-config\-prefix\fP).  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
+\fI\%\-\-show\-suites\fP to display the discovered test suites at startup.
+.sp
+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:
+.sp
+\fBlit_config\fP
+.INDENT 0.0
+.INDENT 3.5
+The global \fBlit\fP configuration object (a \fILitConfig\fP instance), which defines
+the builtin test formats, global configuration parameters, and other helper
+routines for implementing test configurations.
+.UNINDENT
+.UNINDENT
+.sp
+\fBconfig\fP
+.INDENT 0.0
+.INDENT 3.5
+This is the config object (a \fITestingConfig\fP instance) for the test suite,
+which the config file is expected to populate.  The following variables are also
+available on the \fIconfig\fP object, some of which must be set by the config and
+others are optional or predefined:
+.sp
+\fBname\fP \fI[required]\fP The name of the test suite, for use in reports and
+diagnostics.
+.sp
+\fBtest_format\fP \fI[required]\fP 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 \fIlit.formats\fP module.
+.sp
+\fBtest_source_root\fP The filesystem path to the test suite root.  For out\-of\-dir
+builds this is the directory that will be scanned for tests.
+.sp
+\fBtest_exec_root\fP 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.
+.sp
+\fBenvironment\fP A dictionary representing the environment to use when executing
+tests in the suite.
+.sp
+\fBsuffixes\fP For \fBlit\fP test formats which scan directories for tests, this
+variable is a list of suffixes to identify test files.  Used by: \fIShTest\fP\&.
+.sp
+\fBsubstitutions\fP For \fBlit\fP test formats which substitute variables into a test
+script, the list of substitutions to perform.  Used by: \fIShTest\fP\&.
+.sp
+\fBunsupported\fP Mark an unsupported directory, all tests within it will be
+reported as unsupported.  Used by: \fIShTest\fP\&.
+.sp
+\fBparent\fP The parent configuration, this is the config object for the directory
+containing the test suite, or None.
+.sp
+\fBroot\fP The root configuration.  This is the top\-most \fBlit\fP configuration in
+the project.
+.sp
+\fBpipefail\fP Normally a test using a shell pipe fails if any of the commands
+on the pipe fail. If this is not desired, setting this variable to false
+makes the test fail only if the last command in the pipe fails.
+.UNINDENT
+.UNINDENT
+.SS TEST DISCOVERY
+.sp
+Once test suites are located, \fBlit\fP recursively traverses the source
+directory (following \fItest_source_root\fP) looking for tests.  When \fBlit\fP
+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
+\fI\%LOCAL CONFIGURATION FILES\fP).
+.sp
+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 \fIGoogleTest\fP) 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.
+.SS LOCAL CONFIGURATION FILES
+.sp
+When \fBlit\fP loads a subdirectory in a test suite, it instantiates a
+local test configuration by cloning the configuration for the parent directory
+\-\-\- the root of this configuration chain will always be a test suite.  Once the
+test configuration is cloned \fBlit\fP checks for a \fIlit.local.cfg\fP 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.
+.SS TEST RUN OUTPUT FORMAT
+.sp
+The \fBlit\fP 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.
+.sp
+Each test result is expected to appear on a line that matches:
+.INDENT 0.0
+.INDENT 3.5
+.sp
+.nf
+.ft C
+<result code>: <test name> (<progress info>)
+.ft P
+.fi
+.UNINDENT
+.UNINDENT
+.sp
+where \fB<result\-code>\fP 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.
+.sp
+The \fB<test name>\fP field can consist of an arbitrary string containing no
+newline.
+.sp
+The \fB<progress info>\fP field can be used to report progress information such
+as (1/300) or can be empty, but even when empty the parentheses are required.
+.sp
+Each test result may include additional (multiline) log information in the
+following format:
+.INDENT 0.0
+.INDENT 3.5
+.sp
+.nf
+.ft C
+<log delineator> TEST \(aq(<test name>)\(aq <trailing delineator>
+\&... log message ...
+<log delineator>
+.ft P
+.fi
+.UNINDENT
+.UNINDENT
+.sp
+where \fB<test name>\fP should be the name of a preceding reported test, \fB<log
+delineator>\fP is a string of "*" characters \fIat least\fP four characters long
+(the recommended length is 20), and \fB<trailing delineator>\fP is an arbitrary
+(unparsed) string.
+.sp
+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:
+.INDENT 0.0
+.INDENT 3.5
+.sp
+.nf
+.ft C
+PASS: A (1 of 4)
+PASS: B (2 of 4)
+FAIL: C (3 of 4)
+******************** TEST \(aqC\(aq FAILED ********************
+Test \(aqC\(aq failed as a result of exit code 1.
+********************
+PASS: D (4 of 4)
+.ft P
+.fi
+.UNINDENT
+.UNINDENT
+.SS LIT EXAMPLE TESTS
+.sp
+The \fBlit\fP distribution contains several example implementations of
+test suites in the \fIExampleTests\fP directory.
+.SH SEE ALSO
+.sp
+valgrind(1)
+.SH AUTHOR
+Maintained by The LLVM Team (http://llvm.org/).
+.SH COPYRIGHT
+2003-2016, LLVM Project
+.\" Generated by docutils manpage writer.
+.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/Solaris/man1/llc.1	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,264 @@
+.\" Man page generated from reStructuredText.
+.
+.TH "LLC" "1" "2016-07-10" "3.8" "LLVM"
+.SH NAME
+llc \- LLVM static compiler
+.
+.nr rst2man-indent-level 0
+.
+.de1 rstReportMargin
+\\$1 \\n[an-margin]
+level \\n[rst2man-indent-level]
+level margin: \\n[rst2man-indent\\n[rst2man-indent-level]]
+-
+\\n[rst2man-indent0]
+\\n[rst2man-indent1]
+\\n[rst2man-indent2]
+..
+.de1 INDENT
+.\" .rstReportMargin pre:
+. RS \\$1
+. nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin]
+. nr rst2man-indent-level +1
+.\" .rstReportMargin post:
+..
+.de UNINDENT
+. RE
+.\" indent \\n[an-margin]
+.\" old: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.nr rst2man-indent-level -1
+.\" new: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.in \\n[rst2man-indent\\n[rst2man-indent-level]]u
+..
+.SH SYNOPSIS
+.sp
+\fBllc\fP [\fIoptions\fP] [\fIfilename\fP]
+.SH DESCRIPTION
+.sp
+The \fBllc\fP 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.
+.sp
+The choice of architecture for the output assembly code is automatically
+determined from the input file, unless the \fB\-march\fP option is used to
+override the default.
+.SH OPTIONS
+.sp
+If \fBfilename\fP is "\fB\-\fP" or omitted, \fBllc\fP reads from standard input.
+Otherwise, it will from \fBfilename\fP\&.  Inputs can be in either the LLVM assembly
+language format (\fB\&.ll\fP) or the LLVM bitcode format (\fB\&.bc\fP).
+.sp
+If the \fB\-o\fP option is omitted, then \fBllc\fP will send its output
+to standard output if the input is from standard input.  If the \fB\-o\fP
+option specifies "\fB\-\fP", then the output will also be sent to standard output.
+.sp
+If no \fB\-o\fP option is specified and an input file other than "\fB\-\fP" is
+specified, then \fBllc\fP creates the output filename by taking the input
+filename, removing any existing \fB\&.bc\fP extension, and adding a \fB\&.s\fP suffix.
+.sp
+Other \fBllc\fP options are described below.
+.SS End\-user Options
+.INDENT 0.0
+.TP
+.B \-help
+Print a summary of command line options.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-O=uint
+Generate code at different optimization levels.  These correspond to the
+\fB\-O0\fP, \fB\-O1\fP, \fB\-O2\fP, and \fB\-O3\fP optimization levels used by
+\fBclang\fP\&.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-mtriple=<target triple>
+Override the target triple specified in the input file with the specified
+string.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-march=<arch>
+Specify the architecture for which to generate assembly, overriding the target
+encoded in the input file.  See the output of \fBllc \-help\fP for a list of
+valid architectures.  By default this is inferred from the target triple or
+autodetected to the current architecture.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-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:
+.INDENT 7.0
+.INDENT 3.5
+.sp
+.nf
+.ft C
+llvm\-as < /dev/null | llc \-march=xyz \-mcpu=help
+.ft P
+.fi
+.UNINDENT
+.UNINDENT
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-filetype=<output file type>
+Specify what kind of output \fBllc\fP should generated.  Options are: \fBasm\fP
+for textual assembly ( \fB\(aq.s\(aq\fP), \fBobj\fP for native object files (\fB\(aq.o\(aq\fP)
+and \fBnull\fP for not emitting anything (for performance testing).
+.sp
+Note that not all targets support all options.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-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:
+.INDENT 7.0
+.INDENT 3.5
+.sp
+.nf
+.ft C
+llvm\-as < /dev/null | llc \-march=xyz \-mattr=help
+.ft P
+.fi
+.UNINDENT
+.UNINDENT
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-\-disable\-fp\-elim
+Disable frame pointer elimination optimization.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-\-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).
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-\-enable\-no\-infs\-fp\-math
+Enable optimizations that assume no Inf values.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-\-enable\-no\-nans\-fp\-math
+Enable optimizations that assume no NAN values.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-\-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 \fBfsin\fP on X86).
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-\-stats
+Print statistics recorded by code\-generation passes.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-\-time\-passes
+Record the amount of time needed for each pass and print a report to standard
+error.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-\-load=<dso_path>
+Dynamically load \fBdso_path\fP (a path to a dynamically shared object) that
+implements an LLVM target.  This will permit the target name to be used with
+the \fB\-march\fP option so that code can be generated for that target.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-meabi=[default|gnu|4|5]
+Specify which EABI version should conform to.  Valid EABI versions are \fIgnu\fP,
+\fI4\fP and \fI5\fP\&.  Default value (\fIdefault\fP) depends on the triple.
+.UNINDENT
+.SS Tuning/Configuration Options
+.INDENT 0.0
+.TP
+.B \-\-print\-machineinstrs
+Print generated machine code between compilation phases (useful for debugging).
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-\-regalloc=<allocator>
+Specify the register allocator to use.
+Valid register allocators are:
+.sp
+\fIbasic\fP
+.INDENT 7.0
+.INDENT 3.5
+Basic register allocator.
+.UNINDENT
+.UNINDENT
+.sp
+\fIfast\fP
+.INDENT 7.0
+.INDENT 3.5
+Fast register allocator. It is the default for unoptimized code.
+.UNINDENT
+.UNINDENT
+.sp
+\fIgreedy\fP
+.INDENT 7.0
+.INDENT 3.5
+Greedy register allocator. It is the default for optimized code.
+.UNINDENT
+.UNINDENT
+.sp
+\fIpbqp\fP
+.INDENT 7.0
+.INDENT 3.5
+Register allocator based on \(aqPartitioned Boolean Quadratic Programming\(aq.
+.UNINDENT
+.UNINDENT
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-\-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
+\fBspiller\fP is \fIlocal\fP\&.  Valid spillers are:
+.sp
+\fIsimple\fP
+.INDENT 7.0
+.INDENT 3.5
+Simple spiller
+.UNINDENT
+.UNINDENT
+.sp
+\fIlocal\fP
+.INDENT 7.0
+.INDENT 3.5
+Local spiller
+.UNINDENT
+.UNINDENT
+.UNINDENT
+.SS Intel IA\-32\-specific Options
+.INDENT 0.0
+.TP
+.B \-\-x86\-asm\-syntax=[att|intel]
+Specify whether to emit assembly code in AT&T syntax (the default) or Intel
+syntax.
+.UNINDENT
+.SH EXIT STATUS
+.sp
+If \fBllc\fP succeeds, it will exit with 0.  Otherwise, if an error
+occurs, it will exit with a non\-zero value.
+.SH SEE ALSO
+.sp
+lli
+.SH AUTHOR
+Maintained by The LLVM Team (http://llvm.org/).
+.SH COPYRIGHT
+2003-2016, LLVM Project
+.\" Generated by docutils manpage writer.
+.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/Solaris/man1/lli.1	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,297 @@
+.\" Man page generated from reStructuredText.
+.
+.TH "LLI" "1" "2016-07-10" "3.8" "LLVM"
+.SH NAME
+lli \- directly execute programs from LLVM bitcode
+.
+.nr rst2man-indent-level 0
+.
+.de1 rstReportMargin
+\\$1 \\n[an-margin]
+level \\n[rst2man-indent-level]
+level margin: \\n[rst2man-indent\\n[rst2man-indent-level]]
+-
+\\n[rst2man-indent0]
+\\n[rst2man-indent1]
+\\n[rst2man-indent2]
+..
+.de1 INDENT
+.\" .rstReportMargin pre:
+. RS \\$1
+. nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin]
+. nr rst2man-indent-level +1
+.\" .rstReportMargin post:
+..
+.de UNINDENT
+. RE
+.\" indent \\n[an-margin]
+.\" old: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.nr rst2man-indent-level -1
+.\" new: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.in \\n[rst2man-indent\\n[rst2man-indent-level]]u
+..
+.SH SYNOPSIS
+.sp
+\fBlli\fP [\fIoptions\fP] [\fIfilename\fP] [\fIprogram args\fP]
+.SH DESCRIPTION
+.sp
+\fBlli\fP directly executes programs in LLVM bitcode format.  It takes a program
+in LLVM bitcode format and executes it using a just\-in\-time compiler or an
+interpreter.
+.sp
+\fBlli\fP is \fInot\fP an emulator. It will not execute IR of different architectures
+and it can only interpret (or JIT\-compile) for the host architecture.
+.sp
+The JIT compiler takes the same arguments as other tools, like \fBllc\fP,
+but they don\(aqt necessarily work for the interpreter.
+.sp
+If \fIfilename\fP is not specified, then \fBlli\fP reads the LLVM bitcode for the
+program from standard input.
+.sp
+The optional \fIargs\fP specified on the command line are passed to the program as
+arguments.
+.SH GENERAL OPTIONS
+.INDENT 0.0
+.TP
+.B \-fake\-argv0=executable
+Override the \fBargv[0]\fP value passed into the executing program.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-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.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-help
+Print a summary of command line options.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-load=pluginfilename
+Causes \fBlli\fP to load the plugin (shared object) named \fIpluginfilename\fP and use
+it for optimization.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-stats
+Print statistics from the code\-generation passes. This is only meaningful for
+the just\-in\-time compiler, at present.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-time\-passes
+Record the amount of time needed for each code\-generation pass and print it to
+standard error.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-version
+Print out the version of \fBlli\fP and exit without doing anything else.
+.UNINDENT
+.SH TARGET OPTIONS
+.INDENT 0.0
+.TP
+.B \-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.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-march=arch
+Specify the architecture for which to generate assembly, overriding the target
+encoded in the bitcode file.  See the output of \fBllc \-help\fP for a list of
+valid architectures.  By default this is inferred from the target triple or
+autodetected to the current architecture.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-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:
+\fBllvm\-as < /dev/null | llc \-march=xyz \-mcpu=help\fP
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-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:
+\fBllvm\-as < /dev/null | llc \-march=xyz \-mattr=help\fP
+.UNINDENT
+.SH FLOATING POINT OPTIONS
+.INDENT 0.0
+.TP
+.B \-disable\-excess\-fp\-precision
+Disable optimizations that may increase floating point precision.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-enable\-no\-infs\-fp\-math
+Enable optimizations that assume no Inf values.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-enable\-no\-nans\-fp\-math
+Enable optimizations that assume no NAN values.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-enable\-unsafe\-fp\-math
+Causes \fBlli\fP to enable optimizations that may decrease floating point
+precision.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-soft\-float
+Causes \fBlli\fP to generate software floating point library calls instead of
+equivalent hardware instructions.
+.UNINDENT
+.SH CODE GENERATION OPTIONS
+.INDENT 0.0
+.TP
+.B \-code\-model=model
+Choose the code model from:
+.INDENT 7.0
+.INDENT 3.5
+.sp
+.nf
+.ft C
+default: Target default code model
+small: Small code model
+kernel: Kernel code model
+medium: Medium code model
+large: Large code model
+.ft P
+.fi
+.UNINDENT
+.UNINDENT
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-disable\-post\-RA\-scheduler
+Disable scheduling after register allocation.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-disable\-spill\-fusing
+Disable fusing of spill code into instructions.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-jit\-enable\-eh
+Exception handling should be enabled in the just\-in\-time compiler.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-join\-liveintervals
+Coalesce copies (default=true).
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-nozero\-initialized\-in\-bss
+Don\(aqt place zero\-initialized symbols into the BSS section.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-pre\-RA\-sched=scheduler
+Instruction schedulers available (before register allocation):
+.INDENT 7.0
+.INDENT 3.5
+.sp
+.nf
+.ft C
+=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
+.ft P
+.fi
+.UNINDENT
+.UNINDENT
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-regalloc=allocator
+Register allocator to use (default=linearscan)
+.INDENT 7.0
+.INDENT 3.5
+.sp
+.nf
+.ft C
+=bigblock: Big\-block register allocator
+=linearscan: linear scan register allocator =local \-   local register allocator
+=simple: simple register allocator
+.ft P
+.fi
+.UNINDENT
+.UNINDENT
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-relocation\-model=model
+Choose relocation model from:
+.INDENT 7.0
+.INDENT 3.5
+.sp
+.nf
+.ft C
+=default: Target default relocation model
+=static: Non\-relocatable code =pic \-   Fully relocatable, position independent code
+=dynamic\-no\-pic: Relocatable external references, non\-relocatable code
+.ft P
+.fi
+.UNINDENT
+.UNINDENT
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-spiller
+Spiller to use (default=local)
+.INDENT 7.0
+.INDENT 3.5
+.sp
+.nf
+.ft C
+=simple: simple spiller
+=local: local spiller
+.ft P
+.fi
+.UNINDENT
+.UNINDENT
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-x86\-asm\-syntax=syntax
+Choose style of code to emit from X86 backend:
+.INDENT 7.0
+.INDENT 3.5
+.sp
+.nf
+.ft C
+=att: Emit AT&T\-style assembly
+=intel: Emit Intel\-style assembly
+.ft P
+.fi
+.UNINDENT
+.UNINDENT
+.UNINDENT
+.SH EXIT STATUS
+.sp
+If \fBlli\fP 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.
+.SH SEE ALSO
+.sp
+\fBllc\fP
+.SH AUTHOR
+Maintained by The LLVM Team (http://llvm.org/).
+.SH COPYRIGHT
+2003-2016, LLVM Project
+.\" Generated by docutils manpage writer.
+.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/Solaris/man1/llvm-ar.1	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,389 @@
+.\" Man page generated from reStructuredText.
+.
+.TH "LLVM-AR" "1" "2016-07-10" "3.8" "LLVM"
+.SH NAME
+llvm-ar \- LLVM archiver
+.
+.nr rst2man-indent-level 0
+.
+.de1 rstReportMargin
+\\$1 \\n[an-margin]
+level \\n[rst2man-indent-level]
+level margin: \\n[rst2man-indent\\n[rst2man-indent-level]]
+-
+\\n[rst2man-indent0]
+\\n[rst2man-indent1]
+\\n[rst2man-indent2]
+..
+.de1 INDENT
+.\" .rstReportMargin pre:
+. RS \\$1
+. nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin]
+. nr rst2man-indent-level +1
+.\" .rstReportMargin post:
+..
+.de UNINDENT
+. RE
+.\" indent \\n[an-margin]
+.\" old: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.nr rst2man-indent-level -1
+.\" new: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.in \\n[rst2man-indent\\n[rst2man-indent-level]]u
+..
+.SH SYNOPSIS
+.sp
+\fBllvm\-ar\fP [\-]{dmpqrtx}[Rabfikou] [relpos] [count] <archive> [files...]
+.SH DESCRIPTION
+.sp
+The \fBllvm\-ar\fP command is similar to the common Unix utility, \fBar\fP\&. 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,
+\fBllvm\-ar\fP 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.
+.sp
+The \fBllvm\-ar\fP command can be used to \fIread\fP SVR4, GNU and BSD style archive
+files. However, right now it can only write in the GNU format. If an
+SVR4 or BSD style archive is used with the \fBr\fP (replace) or \fBq\fP (quick
+update) operations, the archive will be reconstructed in GNU format.
+.sp
+Here\(aqs where \fBllvm\-ar\fP departs from previous \fBar\fP implementations:
+.sp
+\fISymbol Table\fP
+.INDENT 0.0
+.INDENT 3.5
+Since \fBllvm\-ar\fP supports bitcode files. The symbol table it creates
+is in GNU format and includes both native and bitcode files.
+.UNINDENT
+.UNINDENT
+.sp
+\fILong Paths\fP
+.INDENT 0.0
+.INDENT 3.5
+Currently \fBllvm\-ar\fP can read GNU and BSD long file names, but only writes
+archives with the GNU format.
+.UNINDENT
+.UNINDENT
+.SH OPTIONS
+.sp
+The options to \fBllvm\-ar\fP are compatible with other \fBar\fP implementations.
+However, there are a few modifiers (\fIR\fP) that are not found in other \fBar\fP
+implementations. The options to \fBllvm\-ar\fP 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 \fBllvm\-ar\fP should process the archive file.
+.sp
+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 \fB\&.a\fP suffix, but this is not required. Following
+the \fIarchive\-name\fP comes a list of \fIfiles\fP that indicate the specific members
+of the archive to operate on. If the \fIfiles\fP option is not specified, it
+generally means either "none" or "all" members, depending on the operation.
+.SS Operations
+.sp
+d
+.INDENT 0.0
+.INDENT 3.5
+Delete files from the archive. No modifiers are applicable to this operation.
+The \fIfiles\fP 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 \fIfiles\fP are specified, the archive is not modified.
+.UNINDENT
+.UNINDENT
+.sp
+m[abi]
+.INDENT 0.0
+.INDENT 3.5
+Move files from one location in the archive to another. The \fIa\fP, \fIb\fP, and
+\fIi\fP modifiers apply to this operation. The \fIfiles\fP 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 \fIfiles\fP are specified, the
+archive is not modified.
+.UNINDENT
+.UNINDENT
+.sp
+p
+.INDENT 0.0
+.INDENT 3.5
+Print files to the standard output. This operation simply prints the
+\fIfiles\fP indicated to the standard output. If no \fIfiles\fP are
+specified, the entire  archive is printed.  Printing bitcode files is
+ill\-advised as they might confuse your terminal settings. The \fIp\fP
+operation never modifies the archive.
+.UNINDENT
+.UNINDENT
+.sp
+q
+.INDENT 0.0
+.INDENT 3.5
+Quickly append files to the end of the archive.  This operation quickly adds the
+\fIfiles\fP to the archive without checking for duplicates that should be
+removed first. If no \fIfiles\fP are specified, the archive is not modified.
+Because of the way that \fBllvm\-ar\fP constructs the archive file, its dubious
+whether the \fIq\fP operation is any faster than the \fIr\fP operation.
+.UNINDENT
+.UNINDENT
+.sp
+r[abu]
+.INDENT 0.0
+.INDENT 3.5
+Replace or insert file members. The \fIa\fP, \fIb\fP,  and \fIu\fP
+modifiers apply to this operation. This operation will replace existing
+\fIfiles\fP or insert them at the end of the archive if they do not exist. If no
+\fIfiles\fP are specified, the archive is not modified.
+.UNINDENT
+.UNINDENT
+.sp
+t[v]
+.INDENT 0.0
+.INDENT 3.5
+Print the table of contents. Without any modifiers, this operation just prints
+the names of the members to the standard output. With the \fIv\fP modifier,
+\fBllvm\-ar\fP 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 \fIfiles\fP are specified, the listing is only for
+those files. If no \fIfiles\fP are specified, the table of contents for the
+whole archive is printed.
+.UNINDENT
+.UNINDENT
+.sp
+x[oP]
+.INDENT 0.0
+.INDENT 3.5
+Extract archive members back to files. The \fIo\fP modifier applies to this
+operation. This operation retrieves the indicated \fIfiles\fP from the archive
+and writes them back to the operating system\(aqs file system. If no
+\fIfiles\fP are specified, the entire archive is extract.
+.UNINDENT
+.UNINDENT
+.SS Modifiers (operation specific)
+.sp
+The modifiers below are specific to certain operations. See the Operations
+section (above) to determine which modifiers are applicable to which operations.
+.sp
+[a]
+.INDENT 0.0
+.INDENT 3.5
+When inserting or moving member files, this option specifies the destination of
+the new files as being after the \fIrelpos\fP member. If \fIrelpos\fP is not found,
+the files are placed at the end of the archive.
+.UNINDENT
+.UNINDENT
+.sp
+[b]
+.INDENT 0.0
+.INDENT 3.5
+When inserting or moving member files, this option specifies the destination of
+the new files as being before the \fIrelpos\fP member. If \fIrelpos\fP is not
+found, the files are placed at the end of the archive. This modifier is
+identical to the \fIi\fP modifier.
+.UNINDENT
+.UNINDENT
+.sp
+[i]
+.INDENT 0.0
+.INDENT 3.5
+A synonym for the \fIb\fP option.
+.UNINDENT
+.UNINDENT
+.sp
+[o]
+.INDENT 0.0
+.INDENT 3.5
+When extracting files, this option will cause \fBllvm\-ar\fP to preserve the
+original modification times of the files it writes.
+.UNINDENT
+.UNINDENT
+.sp
+[u]
+.INDENT 0.0
+.INDENT 3.5
+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.
+.UNINDENT
+.UNINDENT
+.SS Modifiers (generic)
+.sp
+The modifiers below may be applied to any operation.
+.sp
+[c]
+.INDENT 0.0
+.INDENT 3.5
+For all operations, \fBllvm\-ar\fP will always create the archive if it doesn\(aqt
+exist. Normally, \fBllvm\-ar\fP will print a warning message indicating that the
+archive is being created. Using this modifier turns off that warning.
+.UNINDENT
+.UNINDENT
+.sp
+[s]
+.INDENT 0.0
+.INDENT 3.5
+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.
+.UNINDENT
+.UNINDENT
+.sp
+[S]
+.INDENT 0.0
+.INDENT 3.5
+This modifier is the opposite of the \fIs\fP modifier. It instructs \fBllvm\-ar\fP to
+not build the symbol table. If both \fIs\fP and \fIS\fP are used, the last modifier to
+occur in the options will prevail.
+.UNINDENT
+.UNINDENT
+.sp
+[v]
+.INDENT 0.0
+.INDENT 3.5
+This modifier instructs \fBllvm\-ar\fP 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.
+.UNINDENT
+.UNINDENT
+.SH STANDARDS
+.sp
+The \fBllvm\-ar\fP utility is intended to provide a superset of the IEEE Std 1003.2
+(POSIX.2) functionality for \fBar\fP\&. \fBllvm\-ar\fP can read both SVR4 and BSD4.4 (or
+Mac OS X) archives. If the \fBf\fP modifier is given to the \fBx\fP or \fBr\fP operations
+then \fBllvm\-ar\fP will write SVR4 compatible archives. Without this modifier,
+\fBllvm\-ar\fP 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.
+.SH FILE FORMAT
+.sp
+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 \fBar\fP commands on those
+operating systems should be able to read LLVM archive files. The details of the
+file format follow.
+.sp
+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.
+.sp
+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.
+.sp
+name \- char[16]
+.INDENT 0.0
+.INDENT 3.5
+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 \fB#1/nnn\fP where \fBnnn\fP provides the length of the name and the \fB#1/\fP
+is literal.  In this case, the actual name of the file is provided in the \fBnnn\fP
+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.
+.UNINDENT
+.UNINDENT
+.sp
+date \- char[12]
+.INDENT 0.0
+.INDENT 3.5
+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.
+.UNINDENT
+.UNINDENT
+.sp
+uid \- char[6]
+.INDENT 0.0
+.INDENT 3.5
+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.
+.UNINDENT
+.UNINDENT
+.sp
+gid \- char[6]
+.INDENT 0.0
+.INDENT 3.5
+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.
+.UNINDENT
+.UNINDENT
+.sp
+mode \- char[8]
+.INDENT 0.0
+.INDENT 3.5
+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.
+.UNINDENT
+.UNINDENT
+.sp
+size \- char[10]
+.INDENT 0.0
+.INDENT 3.5
+This field provides the size of the file, in bytes, encoded as a decimal ASCII
+string.
+.UNINDENT
+.UNINDENT
+.sp
+fmag \- char[2]
+.INDENT 0.0
+.INDENT 3.5
+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.
+.UNINDENT
+.UNINDENT
+.sp
+offset \- vbr encoded 32\-bit integer
+.INDENT 0.0
+.INDENT 3.5
+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.
+.UNINDENT
+.UNINDENT
+.sp
+length \- vbr encoded 32\-bit integer
+.INDENT 0.0
+.INDENT 3.5
+The length item provides the length of the symbol that follows. Like this
+\fIoffset\fP item, the length is variable bit rate encoded.
+.UNINDENT
+.UNINDENT
+.sp
+symbol \- character array
+.INDENT 0.0
+.INDENT 3.5
+The symbol item provides the text of the symbol that is associated with the
+\fIoffset\fP\&. The symbol is not terminated by any character. Its length is provided
+by the \fIlength\fP 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.
+.UNINDENT
+.UNINDENT
+.SH EXIT STATUS
+.sp
+If \fBllvm\-ar\fP 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.
+.SH SEE ALSO
+.sp
+ar(1)
+.SH AUTHOR
+Maintained by The LLVM Team (http://llvm.org/).
+.SH COPYRIGHT
+2003-2016, LLVM Project
+.\" Generated by docutils manpage writer.
+.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/Solaris/man1/llvm-as.1	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,86 @@
+.\" Man page generated from reStructuredText.
+.
+.TH "LLVM-AS" "1" "2016-07-10" "3.8" "LLVM"
+.SH NAME
+llvm-as \- LLVM assembler
+.
+.nr rst2man-indent-level 0
+.
+.de1 rstReportMargin
+\\$1 \\n[an-margin]
+level \\n[rst2man-indent-level]
+level margin: \\n[rst2man-indent\\n[rst2man-indent-level]]
+-
+\\n[rst2man-indent0]
+\\n[rst2man-indent1]
+\\n[rst2man-indent2]
+..
+.de1 INDENT
+.\" .rstReportMargin pre:
+. RS \\$1
+. nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin]
+. nr rst2man-indent-level +1
+.\" .rstReportMargin post:
+..
+.de UNINDENT
+. RE
+.\" indent \\n[an-margin]
+.\" old: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.nr rst2man-indent-level -1
+.\" new: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.in \\n[rst2man-indent\\n[rst2man-indent-level]]u
+..
+.SH SYNOPSIS
+.sp
+\fBllvm\-as\fP [\fIoptions\fP] [\fIfilename\fP]
+.SH DESCRIPTION
+.sp
+\fBllvm\-as\fP 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.
+.sp
+If \fIfilename\fP is omitted or is \fB\-\fP, then \fBllvm\-as\fP reads its input from
+standard input.
+.sp
+If an output file is not specified with the \fB\-o\fP option, then
+\fBllvm\-as\fP sends its output to a file or standard output by following
+these rules:
+.INDENT 0.0
+.IP \(bu 2
+If the input is standard input, then the output is standard output.
+.IP \(bu 2
+If the input is a file that ends with \fB\&.ll\fP, then the output file is of the
+same name, except that the suffix is changed to \fB\&.bc\fP\&.
+.IP \(bu 2
+If the input is a file that does not end with the \fB\&.ll\fP suffix, then the
+output file has the same name as the input file, except that the \fB\&.bc\fP
+suffix is appended.
+.UNINDENT
+.SH OPTIONS
+.INDENT 0.0
+.TP
+\fB\-f\fP
+Enable binary output on terminals.  Normally, \fBllvm\-as\fP will refuse to
+write raw bitcode output if the output stream is a terminal. With this option,
+\fBllvm\-as\fP will write raw bitcode regardless of the output device.
+.TP
+\fB\-help\fP
+Print a summary of command line options.
+.TP
+\fB\-o\fP \fIfilename\fP
+Specify the output file name.  If \fIfilename\fP is \fB\-\fP, then \fBllvm\-as\fP
+sends its output to standard output.
+.UNINDENT
+.SH EXIT STATUS
+.sp
+If \fBllvm\-as\fP succeeds, it will exit with 0.  Otherwise, if an error occurs, it
+will exit with a non\-zero value.
+.SH SEE ALSO
+.sp
+llvm\-dis|llvm\-dis, gccas|gccas
+.SH AUTHOR
+Maintained by The LLVM Team (http://llvm.org/).
+.SH COPYRIGHT
+2003-2016, LLVM Project
+.\" Generated by docutils manpage writer.
+.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/Solaris/man1/llvm-bcanalyzer.1	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,475 @@
+.\" Man page generated from reStructuredText.
+.
+.TH "LLVM-BCANALYZER" "1" "2016-07-10" "3.8" "LLVM"
+.SH NAME
+llvm-bcanalyzer \- LLVM bitcode analyzer
+.
+.nr rst2man-indent-level 0
+.
+.de1 rstReportMargin
+\\$1 \\n[an-margin]
+level \\n[rst2man-indent-level]
+level margin: \\n[rst2man-indent\\n[rst2man-indent-level]]
+-
+\\n[rst2man-indent0]
+\\n[rst2man-indent1]
+\\n[rst2man-indent2]
+..
+.de1 INDENT
+.\" .rstReportMargin pre:
+. RS \\$1
+. nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin]
+. nr rst2man-indent-level +1
+.\" .rstReportMargin post:
+..
+.de UNINDENT
+. RE
+.\" indent \\n[an-margin]
+.\" old: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.nr rst2man-indent-level -1
+.\" new: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.in \\n[rst2man-indent\\n[rst2man-indent-level]]u
+..
+.SH SYNOPSIS
+.sp
+\fBllvm\-bcanalyzer\fP [\fIoptions\fP] [\fIfilename\fP]
+.SH DESCRIPTION
+.sp
+The \fBllvm\-bcanalyzer\fP command is a small utility for analyzing bitcode
+files.  The tool reads a bitcode file (such as generated with the
+\fBllvm\-as\fP 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.
+.sp
+If \fIfilename\fP is omitted or is \fB\-\fP, then \fBllvm\-bcanalyzer\fP reads its
+input from standard input.  This is useful for combining the tool into a
+pipeline.  Output is written to the standard output.
+.SH OPTIONS
+.INDENT 0.0
+.TP
+.B \-nodetails
+Causes \fBllvm\-bcanalyzer\fP to abbreviate its output by writing out only
+a module level summary.  The details for individual functions are not
+displayed.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-dump
+Causes \fBllvm\-bcanalyzer\fP 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.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-verify
+Causes \fBllvm\-bcanalyzer\fP to verify the module produced by reading the
+bitcode.  This ensures that the statistics generated are based on a consistent
+module.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-help
+Print a summary of command line options.
+.UNINDENT
+.SH EXIT STATUS
+.sp
+If \fBllvm\-bcanalyzer\fP succeeds, it will exit with 0.  Otherwise, if an
+error occurs, it will exit with a non\-zero value, usually 1.
+.SH SUMMARY OUTPUT DEFINITIONS
+.sp
+The following items are always printed by llvm\-bcanalyzer.  They comprize the
+summary output.
+.sp
+\fBBitcode Analysis Of Module\fP
+.INDENT 0.0
+.INDENT 3.5
+This just provides the name of the module for which bitcode analysis is being
+generated.
+.UNINDENT
+.UNINDENT
+.sp
+\fBBitcode Version Number\fP
+.INDENT 0.0
+.INDENT 3.5
+The bitcode version (not LLVM version) of the file read by the analyzer.
+.UNINDENT
+.UNINDENT
+.sp
+\fBFile Size\fP
+.INDENT 0.0
+.INDENT 3.5
+The size, in bytes, of the entire bitcode file.
+.UNINDENT
+.UNINDENT
+.sp
+\fBModule Bytes\fP
+.INDENT 0.0
+.INDENT 3.5
+The size, in bytes, of the module block.  Percentage is relative to File Size.
+.UNINDENT
+.UNINDENT
+.sp
+\fBFunction Bytes\fP
+.INDENT 0.0
+.INDENT 3.5
+The size, in bytes, of all the function blocks.  Percentage is relative to File
+Size.
+.UNINDENT
+.UNINDENT
+.sp
+\fBGlobal Types Bytes\fP
+.INDENT 0.0
+.INDENT 3.5
+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.
+.UNINDENT
+.UNINDENT
+.sp
+\fBConstant Pool Bytes\fP
+.INDENT 0.0
+.INDENT 3.5
+The size, in bytes, of the Constant Pool Blocks Percentage is relative to File
+Size.
+.UNINDENT
+.UNINDENT
+.sp
+\fBModule Globals Bytes\fP
+.INDENT 0.0
+.INDENT 3.5
+Ths size, in bytes, of the Global Variable Definitions and their initializers.
+Percentage is relative to File Size.
+.UNINDENT
+.UNINDENT
+.sp
+\fBInstruction List Bytes\fP
+.INDENT 0.0
+.INDENT 3.5
+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.
+.UNINDENT
+.UNINDENT
+.sp
+\fBCompaction Table Bytes\fP
+.INDENT 0.0
+.INDENT 3.5
+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.
+.UNINDENT
+.UNINDENT
+.sp
+\fBSymbol Table Bytes\fP
+.INDENT 0.0
+.INDENT 3.5
+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.
+.UNINDENT
+.UNINDENT
+.sp
+\fBDependent Libraries Bytes\fP
+.INDENT 0.0
+.INDENT 3.5
+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.
+.UNINDENT
+.UNINDENT
+.sp
+\fBNumber Of Bitcode Blocks\fP
+.INDENT 0.0
+.INDENT 3.5
+The total number of blocks of any kind in the bitcode file.
+.UNINDENT
+.UNINDENT
+.sp
+\fBNumber Of Functions\fP
+.INDENT 0.0
+.INDENT 3.5
+The total number of function definitions in the bitcode file.
+.UNINDENT
+.UNINDENT
+.sp
+\fBNumber Of Types\fP
+.INDENT 0.0
+.INDENT 3.5
+The total number of types defined in the Global Types Pool.
+.UNINDENT
+.UNINDENT
+.sp
+\fBNumber Of Constants\fP
+.INDENT 0.0
+.INDENT 3.5
+The total number of constants (of any type) defined in the Constant Pool.
+.UNINDENT
+.UNINDENT
+.sp
+\fBNumber Of Basic Blocks\fP
+.INDENT 0.0
+.INDENT 3.5
+The total number of basic blocks defined in all functions in the bitcode file.
+.UNINDENT
+.UNINDENT
+.sp
+\fBNumber Of Instructions\fP
+.INDENT 0.0
+.INDENT 3.5
+The total number of instructions defined in all functions in the bitcode file.
+.UNINDENT
+.UNINDENT
+.sp
+\fBNumber Of Long Instructions\fP
+.INDENT 0.0
+.INDENT 3.5
+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.
+.UNINDENT
+.UNINDENT
+.sp
+\fBNumber Of Operands\fP
+.INDENT 0.0
+.INDENT 3.5
+The total number of operands used in all instructions in the bitcode file.
+.UNINDENT
+.UNINDENT
+.sp
+\fBNumber Of Compaction Tables\fP
+.INDENT 0.0
+.INDENT 3.5
+The total number of compaction tables in all functions in the bitcode file.
+.UNINDENT
+.UNINDENT
+.sp
+\fBNumber Of Symbol Tables\fP
+.INDENT 0.0
+.INDENT 3.5
+The total number of symbol tables in all functions in the bitcode file.
+.UNINDENT
+.UNINDENT
+.sp
+\fBNumber Of Dependent Libs\fP
+.INDENT 0.0
+.INDENT 3.5
+The total number of dependent libraries found in the bitcode file.
+.UNINDENT
+.UNINDENT
+.sp
+\fBTotal Instruction Size\fP
+.INDENT 0.0
+.INDENT 3.5
+The total size of the instructions in all functions in the bitcode file.
+.UNINDENT
+.UNINDENT
+.sp
+\fBAverage Instruction Size\fP
+.INDENT 0.0
+.INDENT 3.5
+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.
+.UNINDENT
+.UNINDENT
+.sp
+\fBMaximum Type Slot Number\fP
+.INDENT 0.0
+.INDENT 3.5
+The maximum value used for a type\(aqs slot number.  Larger slot number values take
+more bytes to encode.
+.UNINDENT
+.UNINDENT
+.sp
+\fBMaximum Value Slot Number\fP
+.INDENT 0.0
+.INDENT 3.5
+The maximum value used for a value\(aqs slot number.  Larger slot number values take
+more bytes to encode.
+.UNINDENT
+.UNINDENT
+.sp
+\fBBytes Per Value\fP
+.INDENT 0.0
+.INDENT 3.5
+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.
+.UNINDENT
+.UNINDENT
+.sp
+\fBBytes Per Global\fP
+.INDENT 0.0
+.INDENT 3.5
+The average size of a global definition (constants and global variables).
+.UNINDENT
+.UNINDENT
+.sp
+\fBBytes Per Function\fP
+.INDENT 0.0
+.INDENT 3.5
+The average number of bytes per function definition.  This is computed by
+dividing Function Bytes by Number Of Functions.
+.UNINDENT
+.UNINDENT
+.sp
+\fB# of VBR 32\-bit Integers\fP
+.INDENT 0.0
+.INDENT 3.5
+The total number of 32\-bit integers encoded using the Variable Bit Rate
+encoding scheme.
+.UNINDENT
+.UNINDENT
+.sp
+\fB# of VBR 64\-bit Integers\fP
+.INDENT 0.0
+.INDENT 3.5
+The total number of 64\-bit integers encoded using the Variable Bit Rate encoding
+scheme.
+.UNINDENT
+.UNINDENT
+.sp
+\fB# of VBR Compressed Bytes\fP
+.INDENT 0.0
+.INDENT 3.5
+The total number of bytes consumed by the 32\-bit and 64\-bit integers that use
+the Variable Bit Rate encoding scheme.
+.UNINDENT
+.UNINDENT
+.sp
+\fB# of VBR Expanded Bytes\fP
+.INDENT 0.0
+.INDENT 3.5
+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.
+.UNINDENT
+.UNINDENT
+.sp
+\fBBytes Saved With VBR\fP
+.INDENT 0.0
+.INDENT 3.5
+The total number of bytes saved by using the Variable Bit Rate encoding scheme.
+The percentage is relative to # of VBR Expanded Bytes.
+.UNINDENT
+.UNINDENT
+.SH DETAILED OUTPUT DEFINITIONS
+.sp
+The following definitions occur only if the \-nodetails option was not given.
+The detailed output provides additional information on a per\-function basis.
+.sp
+\fBType\fP
+.INDENT 0.0
+.INDENT 3.5
+The type signature of the function.
+.UNINDENT
+.UNINDENT
+.sp
+\fBByte Size\fP
+.INDENT 0.0
+.INDENT 3.5
+The total number of bytes in the function\(aqs block.
+.UNINDENT
+.UNINDENT
+.sp
+\fBBasic Blocks\fP
+.INDENT 0.0
+.INDENT 3.5
+The number of basic blocks defined by the function.
+.UNINDENT
+.UNINDENT
+.sp
+\fBInstructions\fP
+.INDENT 0.0
+.INDENT 3.5
+The number of instructions defined by the function.
+.UNINDENT
+.UNINDENT
+.sp
+\fBLong Instructions\fP
+.INDENT 0.0
+.INDENT 3.5
+The number of instructions using the long instruction format in the function.
+.UNINDENT
+.UNINDENT
+.sp
+\fBOperands\fP
+.INDENT 0.0
+.INDENT 3.5
+The number of operands used by all instructions in the function.
+.UNINDENT
+.UNINDENT
+.sp
+\fBInstruction Size\fP
+.INDENT 0.0
+.INDENT 3.5
+The number of bytes consumed by instructions in the function.
+.UNINDENT
+.UNINDENT
+.sp
+\fBAverage Instruction Size\fP
+.INDENT 0.0
+.INDENT 3.5
+The average number of bytes consumed by the instructions in the function.
+This value is computed by dividing Instruction Size by Instructions.
+.UNINDENT
+.UNINDENT
+.sp
+\fBBytes Per Instruction\fP
+.INDENT 0.0
+.INDENT 3.5
+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.
+.UNINDENT
+.UNINDENT
+.sp
+\fBNumber of VBR 32\-bit Integers\fP
+.INDENT 0.0
+.INDENT 3.5
+The total number of 32\-bit integers found in this function (for any use).
+.UNINDENT
+.UNINDENT
+.sp
+\fBNumber of VBR 64\-bit Integers\fP
+.INDENT 0.0
+.INDENT 3.5
+The total number of 64\-bit integers found in this function (for any use).
+.UNINDENT
+.UNINDENT
+.sp
+\fBNumber of VBR Compressed Bytes\fP
+.INDENT 0.0
+.INDENT 3.5
+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.
+.UNINDENT
+.UNINDENT
+.sp
+\fBNumber of VBR Expanded Bytes\fP
+.INDENT 0.0
+.INDENT 3.5
+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.
+.UNINDENT
+.UNINDENT
+.sp
+\fBBytes Saved With VBR\fP
+.INDENT 0.0
+.INDENT 3.5
+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.
+.UNINDENT
+.UNINDENT
+.SH SEE ALSO
+.sp
+/CommandGuide/llvm\-dis, /BitCodeFormat
+.SH AUTHOR
+Maintained by The LLVM Team (http://llvm.org/).
+.SH COPYRIGHT
+2003-2016, LLVM Project
+.\" Generated by docutils manpage writer.
+.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/Solaris/man1/llvm-build.1	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,129 @@
+.\" Man page generated from reStructuredText.
+.
+.TH "LLVM-BUILD" "1" "2016-07-10" "3.8" "LLVM"
+.SH NAME
+llvm-build \- LLVM Project Build Utility
+.
+.nr rst2man-indent-level 0
+.
+.de1 rstReportMargin
+\\$1 \\n[an-margin]
+level \\n[rst2man-indent-level]
+level margin: \\n[rst2man-indent\\n[rst2man-indent-level]]
+-
+\\n[rst2man-indent0]
+\\n[rst2man-indent1]
+\\n[rst2man-indent2]
+..
+.de1 INDENT
+.\" .rstReportMargin pre:
+. RS \\$1
+. nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin]
+. nr rst2man-indent-level +1
+.\" .rstReportMargin post:
+..
+.de UNINDENT
+. RE
+.\" indent \\n[an-margin]
+.\" old: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.nr rst2man-indent-level -1
+.\" new: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.in \\n[rst2man-indent\\n[rst2man-indent-level]]u
+..
+.SH SYNOPSIS
+.sp
+\fBllvm\-build\fP [\fIoptions\fP]
+.SH DESCRIPTION
+.sp
+\fBllvm\-build\fP is a tool for working with LLVM projects that use the LLVMBuild
+system for describing their components.
+.sp
+At heart, \fBllvm\-build\fP is responsible for loading, verifying, and manipulating
+the project\(aqs component data. The tool is primarily designed for use in
+implementing build systems and tools which need access to the project structure
+information.
+.SH OPTIONS
+.sp
+\fB\-h\fP, \fB\-\-help\fP
+.INDENT 0.0
+.INDENT 3.5
+Print the builtin program help.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-source\-root\fP=\fIPATH\fP
+.INDENT 0.0
+.INDENT 3.5
+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 \fBllvm\-build\fP script itself.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-print\-tree\fP
+.INDENT 0.0
+.INDENT 3.5
+Print the component tree for the project.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-write\-library\-table\fP
+.INDENT 0.0
+.INDENT 3.5
+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.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-write\-llvmbuild\fP
+.INDENT 0.0
+.INDENT 3.5
+Write out new \fILLVMBuild.txt\fP files based on the loaded components. This is
+useful for auto\-upgrading the schema of the files. \fBllvm\-build\fP 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 \fILLVMBuild\fP files.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-write\-cmake\-fragment\fP
+.INDENT 0.0
+.INDENT 3.5
+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\(aqs
+top\-level CMakeLists.txt.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-write\-make\-fragment\fP
+.INDENT 0.0
+.INDENT 3.5
+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\(aqs Makefile.rules.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-llvmbuild\-source\-root\fP=\fIPATH\fP
+.INDENT 0.0
+.INDENT 3.5
+If given, expect the \fILLVMBuild\fP 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 \fB\-\-write\-llvmbuild\fP to test changes to
+\fILLVMBuild\fP schema.
+.UNINDENT
+.UNINDENT
+.SH EXIT STATUS
+.sp
+\fBllvm\-build\fP exits with 0 if operation was successful. Otherwise, it will exist
+with a non\-zero value.
+.SH AUTHOR
+Maintained by The LLVM Team (http://llvm.org/).
+.SH COPYRIGHT
+2003-2016, LLVM Project
+.\" Generated by docutils manpage writer.
+.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/Solaris/man1/llvm-config.1	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,209 @@
+.\" Man page generated from reStructuredText.
+.
+.TH "LLVM-CONFIG" "1" "2016-07-10" "3.8" "LLVM"
+.SH NAME
+llvm-config \- Print LLVM compilation options
+.
+.nr rst2man-indent-level 0
+.
+.de1 rstReportMargin
+\\$1 \\n[an-margin]
+level \\n[rst2man-indent-level]
+level margin: \\n[rst2man-indent\\n[rst2man-indent-level]]
+-
+\\n[rst2man-indent0]
+\\n[rst2man-indent1]
+\\n[rst2man-indent2]
+..
+.de1 INDENT
+.\" .rstReportMargin pre:
+. RS \\$1
+. nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin]
+. nr rst2man-indent-level +1
+.\" .rstReportMargin post:
+..
+.de UNINDENT
+. RE
+.\" indent \\n[an-margin]
+.\" old: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.nr rst2man-indent-level -1
+.\" new: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.in \\n[rst2man-indent\\n[rst2man-indent-level]]u
+..
+.SH SYNOPSIS
+.sp
+\fBllvm\-config\fP \fIoption\fP [\fIcomponents\fP\&...]
+.SH DESCRIPTION
+.sp
+\fBllvm\-config\fP 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.
+.SH EXAMPLES
+.sp
+To link against the JIT:
+.INDENT 0.0
+.INDENT 3.5
+.sp
+.nf
+.ft C
+g++ \(gallvm\-config \-\-cxxflags\(ga \-o HowToUseJIT.o \-c HowToUseJIT.cpp
+g++ \(gallvm\-config \-\-ldflags\(ga \-o HowToUseJIT HowToUseJIT.o \e
+    \(gallvm\-config \-\-libs engine bcreader scalaropts\(ga
+.ft P
+.fi
+.UNINDENT
+.UNINDENT
+.SH OPTIONS
+.sp
+\fB\-\-version\fP
+.INDENT 0.0
+.INDENT 3.5
+Print the version number of LLVM.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-help\fP
+.INDENT 0.0
+.INDENT 3.5
+Print a summary of \fBllvm\-config\fP arguments.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-prefix\fP
+.INDENT 0.0
+.INDENT 3.5
+Print the installation prefix for LLVM.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-src\-root\fP
+.INDENT 0.0
+.INDENT 3.5
+Print the source root from which LLVM was built.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-obj\-root\fP
+.INDENT 0.0
+.INDENT 3.5
+Print the object root used to build LLVM.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-bindir\fP
+.INDENT 0.0
+.INDENT 3.5
+Print the installation directory for LLVM binaries.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-includedir\fP
+.INDENT 0.0
+.INDENT 3.5
+Print the installation directory for LLVM headers.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-libdir\fP
+.INDENT 0.0
+.INDENT 3.5
+Print the installation directory for LLVM libraries.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-cxxflags\fP
+.INDENT 0.0
+.INDENT 3.5
+Print the C++ compiler flags needed to use LLVM headers.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-ldflags\fP
+.INDENT 0.0
+.INDENT 3.5
+Print the flags needed to link against LLVM libraries.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-libs\fP
+.INDENT 0.0
+.INDENT 3.5
+Print all the libraries needed to link against the specified LLVM
+\fIcomponents\fP, including any dependencies.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-libnames\fP
+.INDENT 0.0
+.INDENT 3.5
+Similar to \fB\-\-libs\fP, but prints the bare filenames of the libraries
+without \fB\-l\fP or pathnames.  Useful for linking against a not\-yet\-installed
+copy of LLVM.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-libfiles\fP
+.INDENT 0.0
+.INDENT 3.5
+Similar to \fB\-\-libs\fP, 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.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-components\fP
+.INDENT 0.0
+.INDENT 3.5
+Print all valid component names.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-targets\-built\fP
+.INDENT 0.0
+.INDENT 3.5
+Print the component names for all targets supported by this copy of LLVM.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-build\-mode\fP
+.INDENT 0.0
+.INDENT 3.5
+Print the build mode used when LLVM was built (e.g. Debug or Release)
+.UNINDENT
+.UNINDENT
+.SH COMPONENTS
+.sp
+To print a list of all available components, run \fBllvm\-config
+\-\-components\fP\&.  In most cases, components correspond directly to LLVM
+libraries.  Useful "virtual" components include:
+.sp
+\fBall\fP
+.INDENT 0.0
+.INDENT 3.5
+Includes all LLVM libraries.  The default if no components are specified.
+.UNINDENT
+.UNINDENT
+.sp
+\fBbackend\fP
+.INDENT 0.0
+.INDENT 3.5
+Includes either a native backend or the C backend.
+.UNINDENT
+.UNINDENT
+.sp
+\fBengine\fP
+.INDENT 0.0
+.INDENT 3.5
+Includes either a native JIT or the bitcode interpreter.
+.UNINDENT
+.UNINDENT
+.SH EXIT STATUS
+.sp
+If \fBllvm\-config\fP succeeds, it will exit with 0.  Otherwise, if an error
+occurs, it will exit with a non\-zero value.
+.SH AUTHOR
+Maintained by The LLVM Team (http://llvm.org/).
+.SH COPYRIGHT
+2003-2016, LLVM Project
+.\" Generated by docutils manpage writer.
+.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/Solaris/man1/llvm-cov.1	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,318 @@
+.\" Man page generated from reStructuredText.
+.
+.TH "LLVM-COV" "1" "2016-07-10" "3.8" "LLVM"
+.SH NAME
+llvm-cov \- emit coverage information
+.
+.nr rst2man-indent-level 0
+.
+.de1 rstReportMargin
+\\$1 \\n[an-margin]
+level \\n[rst2man-indent-level]
+level margin: \\n[rst2man-indent\\n[rst2man-indent-level]]
+-
+\\n[rst2man-indent0]
+\\n[rst2man-indent1]
+\\n[rst2man-indent2]
+..
+.de1 INDENT
+.\" .rstReportMargin pre:
+. RS \\$1
+. nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin]
+. nr rst2man-indent-level +1
+.\" .rstReportMargin post:
+..
+.de UNINDENT
+. RE
+.\" indent \\n[an-margin]
+.\" old: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.nr rst2man-indent-level -1
+.\" new: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.in \\n[rst2man-indent\\n[rst2man-indent-level]]u
+..
+.SH SYNOPSIS
+.sp
+\fBllvm\-cov\fP \fIcommand\fP [\fIargs...\fP]
+.SH DESCRIPTION
+.sp
+The \fBllvm\-cov\fP tool shows code coverage information for
+programs that are instrumented to emit profile data. It can be used to
+work with \fBgcov\fP\-style coverage or with \fBclang\fP\(aqs instrumentation
+based profiling.
+.sp
+If the program is invoked with a base name of \fBgcov\fP, it will behave as if
+the \fBllvm\-cov gcov\fP command were called. Otherwise, a command should
+be provided.
+.SH COMMANDS
+.INDENT 0.0
+.IP \(bu 2
+\fI\%gcov\fP
+.IP \(bu 2
+\fI\%show\fP
+.IP \(bu 2
+\fI\%report\fP
+.UNINDENT
+.SH GCOV COMMAND
+.SS SYNOPSIS
+.sp
+\fBllvm\-cov gcov\fP [\fIoptions\fP] \fISOURCEFILE\fP
+.SS DESCRIPTION
+.sp
+The \fBllvm\-cov gcov\fP tool reads code coverage data files and displays
+the coverage information for a specified source file. It is compatible with the
+\fBgcov\fP tool from version 4.2 of \fBGCC\fP and may also be compatible with some
+later versions of \fBgcov\fP\&.
+.sp
+To use \fBllvm\-cov gcov\fP, you must first build an instrumented version
+of your application that collects coverage data as it runs. Compile with the
+\fB\-fprofile\-arcs\fP and \fB\-ftest\-coverage\fP options to add the
+instrumentation. (Alternatively, you can use the \fB\-\-coverage\fP option, which
+includes both of those other options.) You should compile with debugging
+information (\fB\-g\fP) and without optimization (\fB\-O0\fP); otherwise, the
+coverage data cannot be accurately mapped back to the source code.
+.sp
+At the time you compile the instrumented code, a \fB\&.gcno\fP data file will be
+generated for each object file. These \fB\&.gcno\fP files contain half of the
+coverage data. The other half of the data comes from \fB\&.gcda\fP files that are
+generated when you run the instrumented program, with a separate \fB\&.gcda\fP
+file for each object file. Each time you run the program, the execution counts
+are summed into any existing \fB\&.gcda\fP files, so be sure to remove any old
+files if you do not want their contents to be included.
+.sp
+By default, the \fB\&.gcda\fP files are written into the same directory as the
+object files, but you can override that by setting the \fBGCOV_PREFIX\fP and
+\fBGCOV_PREFIX_STRIP\fP environment variables. The \fBGCOV_PREFIX_STRIP\fP
+variable specifies a number of directory components to be removed from the
+start of the absolute path to the object file directory. After stripping those
+directories, the prefix from the \fBGCOV_PREFIX\fP variable is added. These
+environment variables allow you to run the instrumented program on a machine
+where the original object file directories are not accessible, but you will
+then need to copy the \fB\&.gcda\fP files back to the object file directories
+where \fBllvm\-cov gcov\fP expects to find them.
+.sp
+Once you have generated the coverage data files, run \fBllvm\-cov gcov\fP
+for each main source file where you want to examine the coverage results. This
+should be run from the same directory where you previously ran the
+compiler. The results for the specified source file are written to a file named
+by appending a \fB\&.gcov\fP suffix. A separate output file is also created for
+each file included by the main source file, also with a \fB\&.gcov\fP suffix added.
+.sp
+The basic content of an \fB\&.gcov\fP output file is a copy of the source file with
+an execution count and line number prepended to every line. The execution
+count is shown as \fB\-\fP if a line does not contain any executable code. If
+a line contains code but that code was never executed, the count is displayed
+as \fB#####\fP\&.
+.SS OPTIONS
+.INDENT 0.0
+.TP
+.B \-a, \-\-all\-blocks
+Display all basic blocks. If there are multiple blocks for a single line of
+source code, this option causes llvm\-cov to show the count for each block
+instead of just one count for the entire line.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-b, \-\-branch\-probabilities
+Display conditional branch probabilities and a summary of branch information.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-c, \-\-branch\-counts
+Display branch counts instead of probabilities (requires \-b).
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-f, \-\-function\-summaries
+Show a summary of coverage for each function instead of just one summary for
+an entire source file.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-\-help
+Display available options (\-\-help\-hidden for more).
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-l, \-\-long\-file\-names
+For coverage output of files included from the main source file, add the
+main file name followed by \fB##\fP as a prefix to the output file names. This
+can be combined with the \-\-preserve\-paths option to use complete paths for
+both the main file and the included file.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-n, \-\-no\-output
+Do not output any \fB\&.gcov\fP files. Summary information is still
+displayed.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-o=<DIR|FILE>, \-\-object\-directory=<DIR>, \-\-object\-file=<FILE>
+Find objects in DIR or based on FILE\(aqs path. If you specify a particular
+object file, the coverage data files are expected to have the same base name
+with \fB\&.gcno\fP and \fB\&.gcda\fP extensions. If you specify a directory, the
+files are expected in that directory with the same base name as the source
+file.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-p, \-\-preserve\-paths
+Preserve path components when naming the coverage output files. In addition
+to the source file name, include the directories from the path to that
+file. The directories are separate by \fB#\fP characters, with \fB\&.\fP directories
+removed and \fB\&..\fP directories replaced by \fB^\fP characters. When used with
+the \-\-long\-file\-names option, this applies to both the main file name and the
+included file name.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-u, \-\-unconditional\-branches
+Include unconditional branches in the output for the \-\-branch\-probabilities
+option.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-version
+Display the version of llvm\-cov.
+.UNINDENT
+.SS EXIT STATUS
+.sp
+\fBllvm\-cov gcov\fP returns 1 if it cannot read input files.  Otherwise,
+it exits with zero.
+.SH SHOW COMMAND
+.SS SYNOPSIS
+.sp
+\fBllvm\-cov show\fP [\fIoptions\fP] \-instr\-profile \fIPROFILE\fP \fIBIN\fP [\fISOURCES\fP]
+.SS DESCRIPTION
+.sp
+The \fBllvm\-cov show\fP command shows line by line coverage of a binary
+\fIBIN\fP using the profile data \fIPROFILE\fP\&. It can optionally be filtered to only
+show the coverage for the files listed in \fISOURCES\fP\&.
+.sp
+To use \fBllvm\-cov show\fP, you need a program that is compiled with
+instrumentation to emit profile and coverage data. To build such a program with
+\fBclang\fP use the \fB\-fprofile\-instr\-generate\fP and \fB\-fcoverage\-mapping\fP
+flags. If linking with the \fBclang\fP driver, pass \fB\-fprofile\-instr\-generate\fP
+to the link stage to make sure the necessary runtime libraries are linked in.
+.sp
+The coverage information is stored in the built executable or library itself,
+and this is what you should pass to \fBllvm\-cov show\fP as the \fIBIN\fP
+argument. The profile data is generated by running this instrumented program
+normally. When the program exits it will write out a raw profile file,
+typically called \fBdefault.profraw\fP, which can be converted to a format that
+is suitable for the \fIPROFILE\fP argument using the \fBllvm\-profdata merge\fP
+tool.
+.SS OPTIONS
+.INDENT 0.0
+.TP
+.B \-show\-line\-counts
+Show the execution counts for each line. This is enabled by default, unless
+another \fB\-show\fP option is used.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-show\-expansions
+Expand inclusions, such as preprocessor macros or textual inclusions, inline
+in the display of the source file.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-show\-instantiations
+For source regions that are instantiated multiple times, such as templates in
+\fBC++\fP, show each instantiation separately as well as the combined summary.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-show\-regions
+Show the execution counts for each region by displaying a caret that points to
+the character where the region starts.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-show\-line\-counts\-or\-regions
+Show the execution counts for each line if there is only one region on the
+line, but show the individual regions if there are multiple on the line.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-use\-color[=VALUE]
+Enable or disable color output. By default this is autodetected.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-arch=<name>
+If the covered binary is a universal binary, select the architecture to use.
+It is an error to specify an architecture that is not included in the
+universal binary or to use an architecture that does not match a
+non\-universal binary.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-name=<NAME>
+Show code coverage only for functions with the given name.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-name\-regex=<PATTERN>
+Show code coverage only for functions that match the given regular expression.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-line\-coverage\-gt=<N>
+Show code coverage only for functions with line coverage greater than the
+given threshold.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-line\-coverage\-lt=<N>
+Show code coverage only for functions with line coverage less than the given
+threshold.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-region\-coverage\-gt=<N>
+Show code coverage only for functions with region coverage greater than the
+given threshold.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-region\-coverage\-lt=<N>
+Show code coverage only for functions with region coverage less than the given
+threshold.
+.UNINDENT
+.SH REPORT COMMAND
+.SS SYNOPSIS
+.sp
+\fBllvm\-cov report\fP [\fIoptions\fP] \-instr\-profile \fIPROFILE\fP \fIBIN\fP [\fISOURCES\fP]
+.SS DESCRIPTION
+.sp
+The \fBllvm\-cov report\fP command displays a summary of the coverage of a
+binary \fIBIN\fP using the profile data \fIPROFILE\fP\&. It can optionally be filtered to
+only show the coverage for the files listed in \fISOURCES\fP\&.
+.sp
+If no source files are provided, a summary line is printed for each file in the
+coverage data. If any files are provided, summaries are shown for each function
+in the listed files instead.
+.sp
+For information on compiling programs for coverage and generating profile data,
+see \fI\%SHOW COMMAND\fP\&.
+.SS OPTIONS
+.INDENT 0.0
+.TP
+.B \-use\-color[=VALUE]
+Enable or disable color output. By default this is autodetected.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-arch=<name>
+If the covered binary is a universal binary, select the architecture to use.
+It is an error to specify an architecture that is not included in the
+universal binary or to use an architecture that does not match a
+non\-universal binary.
+.UNINDENT
+.SH AUTHOR
+Maintained by The LLVM Team (http://llvm.org/).
+.SH COPYRIGHT
+2003-2016, LLVM Project
+.\" Generated by docutils manpage writer.
+.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/Solaris/man1/llvm-diff.1	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,76 @@
+.\" Man page generated from reStructuredText.
+.
+.TH "LLVM-DIFF" "1" "2016-07-10" "3.8" "LLVM"
+.SH NAME
+llvm-diff \- LLVM structural 'diff'
+.
+.nr rst2man-indent-level 0
+.
+.de1 rstReportMargin
+\\$1 \\n[an-margin]
+level \\n[rst2man-indent-level]
+level margin: \\n[rst2man-indent\\n[rst2man-indent-level]]
+-
+\\n[rst2man-indent0]
+\\n[rst2man-indent1]
+\\n[rst2man-indent2]
+..
+.de1 INDENT
+.\" .rstReportMargin pre:
+. RS \\$1
+. nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin]
+. nr rst2man-indent-level +1
+.\" .rstReportMargin post:
+..
+.de UNINDENT
+. RE
+.\" indent \\n[an-margin]
+.\" old: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.nr rst2man-indent-level -1
+.\" new: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.in \\n[rst2man-indent\\n[rst2man-indent-level]]u
+..
+.SH SYNOPSIS
+.sp
+\fBllvm\-diff\fP [\fIoptions\fP] \fImodule 1\fP \fImodule 2\fP [\fIglobal name ...\fP]
+.SH DESCRIPTION
+.sp
+\fBllvm\-diff\fP 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.
+.sp
+An input module will be interpreted as an assembly file if its name
+ends in \(aq.ll\(aq;  otherwise it will be read in as a bitcode file.
+.sp
+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.
+.sp
+\fBllvm\-diff\fP 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.
+.sp
+\fBllvm\-diff\fP is intended as a debugging tool for writers of LLVM
+passes and frontends.  It does not have a stable output format.
+.SH EXIT STATUS
+.sp
+If \fBllvm\-diff\fP finds no differences between the modules, it will exit
+with 0 and produce no output.  Otherwise it will exit with a non\-zero
+value.
+.SH BUGS
+.sp
+Many important differences, like changes in linkage or function
+attributes, are not diagnosed.
+.sp
+Changes in memory behavior (for example, coalescing loads) can cause
+massive detected differences in blocks.
+.SH AUTHOR
+Maintained by The LLVM Team (http://llvm.org/).
+.SH COPYRIGHT
+2003-2016, LLVM Project
+.\" Generated by docutils manpage writer.
+.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/Solaris/man1/llvm-dis.1	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,87 @@
+.\" Man page generated from reStructuredText.
+.
+.TH "LLVM-DIS" "1" "2016-07-10" "3.8" "LLVM"
+.SH NAME
+llvm-dis \- LLVM disassembler
+.
+.nr rst2man-indent-level 0
+.
+.de1 rstReportMargin
+\\$1 \\n[an-margin]
+level \\n[rst2man-indent-level]
+level margin: \\n[rst2man-indent\\n[rst2man-indent-level]]
+-
+\\n[rst2man-indent0]
+\\n[rst2man-indent1]
+\\n[rst2man-indent2]
+..
+.de1 INDENT
+.\" .rstReportMargin pre:
+. RS \\$1
+. nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin]
+. nr rst2man-indent-level +1
+.\" .rstReportMargin post:
+..
+.de UNINDENT
+. RE
+.\" indent \\n[an-margin]
+.\" old: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.nr rst2man-indent-level -1
+.\" new: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.in \\n[rst2man-indent\\n[rst2man-indent-level]]u
+..
+.SH SYNOPSIS
+.sp
+\fBllvm\-dis\fP [\fIoptions\fP] [\fIfilename\fP]
+.SH DESCRIPTION
+.sp
+The \fBllvm\-dis\fP command is the LLVM disassembler.  It takes an LLVM
+bitcode file and converts it into human\-readable LLVM assembly language.
+.sp
+If filename is omitted or specified as \fB\-\fP, \fBllvm\-dis\fP reads its
+input from standard input.
+.sp
+If the input is being read from standard input, then \fBllvm\-dis\fP
+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 \fB\&.ll\fP suffix added (any existing \fB\&.bc\fP suffix will first be
+removed).  You can override the choice of output file using the
+\fB\-o\fP option.
+.SH OPTIONS
+.sp
+\fB\-f\fP
+.INDENT 0.0
+.INDENT 3.5
+Enable binary output on terminals.  Normally, \fBllvm\-dis\fP will refuse to
+write raw bitcode output if the output stream is a terminal. With this option,
+\fBllvm\-dis\fP will write raw bitcode regardless of the output device.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-help\fP
+.INDENT 0.0
+.INDENT 3.5
+Print a summary of command line options.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-o\fP \fIfilename\fP
+.INDENT 0.0
+.INDENT 3.5
+Specify the output file name.  If \fIfilename\fP is \-, then the output is sent
+to standard output.
+.UNINDENT
+.UNINDENT
+.SH EXIT STATUS
+.sp
+If \fBllvm\-dis\fP succeeds, it will exit with 0.  Otherwise, if an error
+occurs, it will exit with a non\-zero value.
+.SH SEE ALSO
+.sp
+llvm\-as|llvm\-as
+.SH AUTHOR
+Maintained by The LLVM Team (http://llvm.org/).
+.SH COPYRIGHT
+2003-2016, LLVM Project
+.\" Generated by docutils manpage writer.
+.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/Solaris/man1/llvm-dwarfdump.1	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,59 @@
+.\" Man page generated from reStructuredText.
+.
+.TH "LLVM-DWARFDUMP" "1" "2016-07-10" "3.8" "LLVM"
+.SH NAME
+llvm-dwarfdump \- print contents of DWARF sections
+.
+.nr rst2man-indent-level 0
+.
+.de1 rstReportMargin
+\\$1 \\n[an-margin]
+level \\n[rst2man-indent-level]
+level margin: \\n[rst2man-indent\\n[rst2man-indent-level]]
+-
+\\n[rst2man-indent0]
+\\n[rst2man-indent1]
+\\n[rst2man-indent2]
+..
+.de1 INDENT
+.\" .rstReportMargin pre:
+. RS \\$1
+. nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin]
+. nr rst2man-indent-level +1
+.\" .rstReportMargin post:
+..
+.de UNINDENT
+. RE
+.\" indent \\n[an-margin]
+.\" old: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.nr rst2man-indent-level -1
+.\" new: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.in \\n[rst2man-indent\\n[rst2man-indent-level]]u
+..
+.SH SYNOPSIS
+.sp
+\fBllvm\-dwarfdump\fP [\fIoptions\fP] [\fIfilenames...\fP]
+.SH DESCRIPTION
+.sp
+\fBllvm\-dwarfdump\fP parses DWARF sections in the object files
+and prints their contents in human\-readable form.
+.SH OPTIONS
+.INDENT 0.0
+.TP
+.B \-debug\-dump=section
+Specify the DWARF section to dump.
+For example, use \fBabbrev\fP to dump the contents of \fB\&.debug_abbrev\fP section,
+\fBloc.dwo\fP to dump the contents of \fB\&.debug_loc.dwo\fP etc.
+See \fBllvm\-dwarfdump \-\-help\fP for the complete list of supported sections.
+Use \fBall\fP to dump all DWARF sections. It is the default.
+.UNINDENT
+.SH EXIT STATUS
+.sp
+\fBllvm\-dwarfdump\fP returns 0 if the input files were parsed and dumped
+successfully. Otherwise, it returns 1.
+.SH AUTHOR
+Maintained by The LLVM Team (http://llvm.org/).
+.SH COPYRIGHT
+2003-2016, LLVM Project
+.\" Generated by docutils manpage writer.
+.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/Solaris/man1/llvm-extract.1	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,128 @@
+.\" Man page generated from reStructuredText.
+.
+.TH "LLVM-EXTRACT" "1" "2016-07-10" "3.8" "LLVM"
+.SH NAME
+llvm-extract \- extract a function from an LLVM module
+.
+.nr rst2man-indent-level 0
+.
+.de1 rstReportMargin
+\\$1 \\n[an-margin]
+level \\n[rst2man-indent-level]
+level margin: \\n[rst2man-indent\\n[rst2man-indent-level]]
+-
+\\n[rst2man-indent0]
+\\n[rst2man-indent1]
+\\n[rst2man-indent2]
+..
+.de1 INDENT
+.\" .rstReportMargin pre:
+. RS \\$1
+. nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin]
+. nr rst2man-indent-level +1
+.\" .rstReportMargin post:
+..
+.de UNINDENT
+. RE
+.\" indent \\n[an-margin]
+.\" old: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.nr rst2man-indent-level -1
+.\" new: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.in \\n[rst2man-indent\\n[rst2man-indent-level]]u
+..
+.SH SYNOPSIS
+.sp
+\fBllvm\-extract\fP [\fIoptions\fP] \fB\-\-func\fP \fIfunction\-name\fP [\fIfilename\fP]
+.SH DESCRIPTION
+.sp
+The \fBllvm\-extract\fP 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.
+.sp
+In addition to extracting the bitcode of the specified function,
+\fBllvm\-extract\fP will also remove unreachable global variables,
+prototypes, and unused types.
+.sp
+The \fBllvm\-extract\fP command reads its input from standard input if
+filename is omitted or if filename is \fB\-\fP\&.  The output is always written to
+standard output, unless the \fB\-o\fP option is specified (see below).
+.SH OPTIONS
+.sp
+\fB\-f\fP
+.INDENT 0.0
+.INDENT 3.5
+Enable binary output on terminals.  Normally, \fBllvm\-extract\fP will
+refuse to write raw bitcode output if the output stream is a terminal.  With
+this option, \fBllvm\-extract\fP will write raw bitcode regardless of the
+output device.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-func\fP \fIfunction\-name\fP
+.INDENT 0.0
+.INDENT 3.5
+Extract the function named \fIfunction\-name\fP from the LLVM bitcode.  May be
+specified multiple times to extract multiple functions at once.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-rfunc\fP \fIfunction\-regular\-expr\fP
+.INDENT 0.0
+.INDENT 3.5
+Extract the function(s) matching \fIfunction\-regular\-expr\fP from the LLVM bitcode.
+All functions matching the regular expression will be extracted.  May be
+specified multiple times.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-glob\fP \fIglobal\-name\fP
+.INDENT 0.0
+.INDENT 3.5
+Extract the global variable named \fIglobal\-name\fP from the LLVM bitcode.  May be
+specified multiple times to extract multiple global variables at once.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-\-rglob\fP \fIglob\-regular\-expr\fP
+.INDENT 0.0
+.INDENT 3.5
+Extract the global variable(s) matching \fIglobal\-regular\-expr\fP from the LLVM
+bitcode.  All global variables matching the regular expression will be
+extracted.  May be specified multiple times.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-help\fP
+.INDENT 0.0
+.INDENT 3.5
+Print a summary of command line options.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-o\fP \fIfilename\fP
+.INDENT 0.0
+.INDENT 3.5
+Specify the output filename.  If filename is "\-" (the default), then
+\fBllvm\-extract\fP sends its output to standard output.
+.UNINDENT
+.UNINDENT
+.sp
+\fB\-S\fP
+.INDENT 0.0
+.INDENT 3.5
+Write output in LLVM intermediate language (instead of bitcode).
+.UNINDENT
+.UNINDENT
+.SH EXIT STATUS
+.sp
+If \fBllvm\-extract\fP succeeds, it will exit with 0.  Otherwise, if an error
+occurs, it will exit with a non\-zero value.
+.SH SEE ALSO
+.sp
+bugpoint
+.SH AUTHOR
+Maintained by The LLVM Team (http://llvm.org/).
+.SH COPYRIGHT
+2003-2016, LLVM Project
+.\" Generated by docutils manpage writer.
+.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/Solaris/man1/llvm-lib.1	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,61 @@
+.\" Man page generated from reStructuredText.
+.
+.TH "LLVM-LIB" "1" "2016-07-10" "3.8" "LLVM"
+.SH NAME
+llvm-lib \- LLVM lib.exe compatible library tool
+.
+.nr rst2man-indent-level 0
+.
+.de1 rstReportMargin
+\\$1 \\n[an-margin]
+level \\n[rst2man-indent-level]
+level margin: \\n[rst2man-indent\\n[rst2man-indent-level]]
+-
+\\n[rst2man-indent0]
+\\n[rst2man-indent1]
+\\n[rst2man-indent2]
+..
+.de1 INDENT
+.\" .rstReportMargin pre:
+. RS \\$1
+. nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin]
+. nr rst2man-indent-level +1
+.\" .rstReportMargin post:
+..
+.de UNINDENT
+. RE
+.\" indent \\n[an-margin]
+.\" old: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.nr rst2man-indent-level -1
+.\" new: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.in \\n[rst2man-indent\\n[rst2man-indent-level]]u
+..
+.SH SYNOPSIS
+.sp
+\fBllvm\-lib\fP [/libpath:<path>] [/out:<output>] [/llvmlibthin]
+[/ignore] [/machine] [/nologo] [files...]
+.SH DESCRIPTION
+.sp
+The \fBllvm\-lib\fP command is intended to be a \fBlib.exe\fP compatible
+tool. See \fI\%https://msdn.microsoft.com/en\-us/library/7ykb2k5f\fP for the
+general description.
+.sp
+\fBllvm\-lib\fP has the following extensions:
+.INDENT 0.0
+.IP \(bu 2
+Bitcode files in symbol tables.
+\fBllvm\-lib\fP includes symbols from both bitcode files and regular
+object files in the symbol table.
+.IP \(bu 2
+Creating thin archives.
+The /llvmlibthin option causes \fBllvm\-lib\fP to create thin archive
+that contain only the symbol table and the header for the various
+members. These files are much smaller, but are not compatible with
+link.exe (lld can handle them).
+.UNINDENT
+.SH AUTHOR
+Maintained by The LLVM Team (http://llvm.org/).
+.SH COPYRIGHT
+2003-2016, LLVM Project
+.\" Generated by docutils manpage writer.
+.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/Solaris/man1/llvm-link.1	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,88 @@
+.\" Man page generated from reStructuredText.
+.
+.TH "LLVM-LINK" "1" "2016-07-10" "3.8" "LLVM"
+.SH NAME
+llvm-link \- LLVM bitcode linker
+.
+.nr rst2man-indent-level 0
+.
+.de1 rstReportMargin
+\\$1 \\n[an-margin]
+level \\n[rst2man-indent-level]
+level margin: \\n[rst2man-indent\\n[rst2man-indent-level]]
+-
+\\n[rst2man-indent0]
+\\n[rst2man-indent1]
+\\n[rst2man-indent2]
+..
+.de1 INDENT
+.\" .rstReportMargin pre:
+. RS \\$1
+. nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin]
+. nr rst2man-indent-level +1
+.\" .rstReportMargin post:
+..
+.de UNINDENT
+. RE
+.\" indent \\n[an-margin]
+.\" old: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.nr rst2man-indent-level -1
+.\" new: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.in \\n[rst2man-indent\\n[rst2man-indent-level]]u
+..
+.SH SYNOPSIS
+.sp
+\fBllvm\-link\fP [\fIoptions\fP] \fIfilename ...\fP
+.SH DESCRIPTION
+.sp
+\fBllvm\-link\fP 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 \fB\-o\fP option is used to specify a filename.
+.SH OPTIONS
+.INDENT 0.0
+.TP
+.B \-f
+Enable binary output on terminals.  Normally, \fBllvm\-link\fP will refuse
+to write raw bitcode output if the output stream is a terminal. With this
+option, \fBllvm\-link\fP will write raw bitcode regardless of the output
+device.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-o filename
+Specify the output file name.  If \fBfilename\fP is "\fB\-\fP", then
+\fBllvm\-link\fP will write its output to standard output.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-S
+Write output in LLVM intermediate language (instead of bitcode).
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-d
+If specified, \fBllvm\-link\fP prints a human\-readable version of the
+output bitcode file to standard error.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-help
+Print a summary of command line options.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-v
+Verbose mode.  Print information about what \fBllvm\-link\fP is doing.
+This typically includes a message for each bitcode file linked in and for each
+library found.
+.UNINDENT
+.SH EXIT STATUS
+.sp
+If \fBllvm\-link\fP succeeds, it will exit with 0.  Otherwise, if an error
+occurs, it will exit with a non\-zero value.
+.SH AUTHOR
+Maintained by The LLVM Team (http://llvm.org/).
+.SH COPYRIGHT
+2003-2016, LLVM Project
+.\" Generated by docutils manpage writer.
+.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/Solaris/man1/llvm-nm.1	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,212 @@
+.\" Man page generated from reStructuredText.
+.
+.TH "LLVM-NM" "1" "2016-07-10" "3.8" "LLVM"
+.SH NAME
+llvm-nm \- list LLVM bitcode and object file's symbol table
+.
+.nr rst2man-indent-level 0
+.
+.de1 rstReportMargin
+\\$1 \\n[an-margin]
+level \\n[rst2man-indent-level]
+level margin: \\n[rst2man-indent\\n[rst2man-indent-level]]
+-
+\\n[rst2man-indent0]
+\\n[rst2man-indent1]
+\\n[rst2man-indent2]
+..
+.de1 INDENT
+.\" .rstReportMargin pre:
+. RS \\$1
+. nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin]
+. nr rst2man-indent-level +1
+.\" .rstReportMargin post:
+..
+.de UNINDENT
+. RE
+.\" indent \\n[an-margin]
+.\" old: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.nr rst2man-indent-level -1
+.\" new: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.in \\n[rst2man-indent\\n[rst2man-indent-level]]u
+..
+.SH SYNOPSIS
+.sp
+\fBllvm\-nm\fP [\fIoptions\fP] [\fIfilenames...\fP]
+.SH DESCRIPTION
+.sp
+The \fBllvm\-nm\fP utility lists the names of symbols from the LLVM bitcode
+files, object files, or \fBar\fP 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 \fI\-\fP is used as a file name,
+\fBllvm\-nm\fP will process a file on its standard input stream.
+.sp
+\fBllvm\-nm\fP\(aqs default output format is the traditional BSD \fBnm\fP
+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.
+.sp
+Type code characters currently supported, and their meanings, are as follows:
+.sp
+U
+.INDENT 0.0
+.INDENT 3.5
+Named object is referenced but undefined in this bitcode file
+.UNINDENT
+.UNINDENT
+.sp
+C
+.INDENT 0.0
+.INDENT 3.5
+Common (multiple definitions link together into one def)
+.UNINDENT
+.UNINDENT
+.sp
+W
+.INDENT 0.0
+.INDENT 3.5
+Weak reference (multiple definitions link together into zero or one definitions)
+.UNINDENT
+.UNINDENT
+.sp
+t
+.INDENT 0.0
+.INDENT 3.5
+Local function (text) object
+.UNINDENT
+.UNINDENT
+.sp
+T
+.INDENT 0.0
+.INDENT 3.5
+Global function (text) object
+.UNINDENT
+.UNINDENT
+.sp
+d
+.INDENT 0.0
+.INDENT 3.5
+Local data object
+.UNINDENT
+.UNINDENT
+.sp
+D
+.INDENT 0.0
+.INDENT 3.5
+Global data object
+.UNINDENT
+.UNINDENT
+.sp
+?
+.INDENT 0.0
+.INDENT 3.5
+Something unrecognizable
+.UNINDENT
+.UNINDENT
+.sp
+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", \fBllvm\-nm\fP does not print an address for any
+symbol in an LLVM bitcode file, even symbols which are defined in the bitcode
+file.
+.SH OPTIONS
+.INDENT 0.0
+.TP
+.B \-B    (default)
+Use BSD output format.  Alias for \fB\-\-format=bsd\fP\&.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-P
+Use POSIX.2 output format.  Alias for \fB\-\-format=posix\fP\&.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-\-debug\-syms, \-a
+Show all symbols, even debugger only.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-\-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.)
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-\-dynamic, \-D
+Display dynamic symbols instead of normal symbols.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-\-extern\-only, \-g
+Print only symbols whose definitions are external; that is, accessible
+from other files.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-\-format=format, \-f format
+Select an output format; \fIformat\fP may be \fIsysv\fP, \fIposix\fP, or \fIbsd\fP\&.  The default
+is \fIbsd\fP\&.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-help
+Print a summary of command\-line options and their meanings.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-\-no\-sort, \-p
+Shows symbols in order encountered.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-\-numeric\-sort, \-n, \-v
+Sort symbols by address.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-\-print\-file\-name, \-A, \-o
+Precede each symbol with the file it came from.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-\-print\-size, \-S
+Show symbol size instead of address.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-\-size\-sort
+Sort symbols by size.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-\-undefined\-only, \-u
+Print only symbols referenced but not defined in this file.
+.UNINDENT
+.SH BUGS
+.INDENT 0.0
+.INDENT 3.5
+.INDENT 0.0
+.IP \(bu 2
+\fBllvm\-nm\fP cannot demangle C++ mangled names, like GNU \fBnm\fP
+can.
+.IP \(bu 2
+\fBllvm\-nm\fP does not support the full set of arguments that GNU
+\fBnm\fP does.
+.UNINDENT
+.UNINDENT
+.UNINDENT
+.SH EXIT STATUS
+.sp
+\fBllvm\-nm\fP exits with an exit code of zero.
+.SH SEE ALSO
+.sp
+llvm\-dis, ar(1), nm(1)
+.SH AUTHOR
+Maintained by The LLVM Team (http://llvm.org/).
+.SH COPYRIGHT
+2003-2016, LLVM Project
+.\" Generated by docutils manpage writer.
+.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/Solaris/man1/llvm-profdata.1	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,222 @@
+.\" Man page generated from reStructuredText.
+.
+.TH "LLVM-PROFDATA" "1" "2016-07-10" "3.8" "LLVM"
+.SH NAME
+llvm-profdata \- Profile data tool
+.
+.nr rst2man-indent-level 0
+.
+.de1 rstReportMargin
+\\$1 \\n[an-margin]
+level \\n[rst2man-indent-level]
+level margin: \\n[rst2man-indent\\n[rst2man-indent-level]]
+-
+\\n[rst2man-indent0]
+\\n[rst2man-indent1]
+\\n[rst2man-indent2]
+..
+.de1 INDENT
+.\" .rstReportMargin pre:
+. RS \\$1
+. nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin]
+. nr rst2man-indent-level +1
+.\" .rstReportMargin post:
+..
+.de UNINDENT
+. RE
+.\" indent \\n[an-margin]
+.\" old: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.nr rst2man-indent-level -1
+.\" new: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.in \\n[rst2man-indent\\n[rst2man-indent-level]]u
+..
+.SH SYNOPSIS
+.sp
+\fBllvm\-profdata\fP \fIcommand\fP [\fIargs...\fP]
+.SH DESCRIPTION
+.sp
+The \fBllvm\-profdata\fP tool is a small utility for working with profile
+data files.
+.SH COMMANDS
+.INDENT 0.0
+.IP \(bu 2
+\fI\%merge\fP
+.IP \(bu 2
+\fI\%show\fP
+.UNINDENT
+.SH MERGE
+.SS SYNOPSIS
+.sp
+\fBllvm\-profdata merge\fP [\fIoptions\fP] [\fIfilename...\fP]
+.SS DESCRIPTION
+.sp
+\fBllvm\-profdata merge\fP takes several profile data files
+generated by PGO instrumentation and merges them together into a single
+indexed profile data file.
+.sp
+By default profile data is merged without modification. This means that the
+relative importance of each input file is proportional to the number of samples
+or counts it contains. In general, the input from a longer training run will be
+interpreted as relatively more important than a shorter run. Depending on the
+nature of the training runs it may be useful to adjust the weight given to each
+input file by using the \fB\-weighted\-input\fP option.
+.SS OPTIONS
+.INDENT 0.0
+.TP
+.B \-help
+Print a summary of command line options.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-output=output, \-o=output
+Specify the output file name.  \fIOutput\fP cannot be \fB\-\fP as the resulting
+indexed profile data can\(aqt be written to standard output.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-weighted\-input=weight,filename
+Specify an input file name along with a weight. The profile counts of the input
+file will be scaled (multiplied) by the supplied \fBweight\fP, where where \fBweight\fP
+is a decimal integer >= 1. Input files specified without using this option are
+assigned a default weight of 1. Examples are shown below.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-instr (default)
+Specify that the input profile is an instrumentation\-based profile.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-sample
+Specify that the input profile is a sample\-based profile.
+.sp
+The format of the generated file can be generated in one of three ways:
+.INDENT 7.0
+.TP
+.B \-binary (default)
+.UNINDENT
+.sp
+Emit the profile using a binary encoding. For instrumentation\-based profile
+the output format is the indexed binary format.
+.INDENT 7.0
+.TP
+.B \-text
+.UNINDENT
+.sp
+Emit the profile in text mode. This option can also be used with both
+sample\-based and instrumentation\-based profile. When this option is used
+the profile will be dumped in the text format that is parsable by the profile
+reader.
+.INDENT 7.0
+.TP
+.B \-gcc
+.UNINDENT
+.sp
+Emit the profile using GCC\(aqs gcov format (Not yet supported).
+.UNINDENT
+.SS EXAMPLES
+.SS Basic Usage
+.sp
+Merge three profiles:
+.INDENT 0.0
+.INDENT 3.5
+.sp
+.nf
+.ft C
+llvm\-profdata merge foo.profdata bar.profdata baz.profdata \-output merged.profdata
+.ft P
+.fi
+.UNINDENT
+.UNINDENT
+.SS Weighted Input
+.sp
+The input file \fIfoo.profdata\fP is especially important, multiply its counts by 10:
+.INDENT 0.0
+.INDENT 3.5
+.sp
+.nf
+.ft C
+llvm\-profdata merge \-weighted\-input=10,foo.profdata bar.profdata baz.profdata \-output merged.profdata
+.ft P
+.fi
+.UNINDENT
+.UNINDENT
+.sp
+Exactly equivalent to the previous invocation (explicit form; useful for programmatic invocation):
+.INDENT 0.0
+.INDENT 3.5
+.sp
+.nf
+.ft C
+llvm\-profdata merge \-weighted\-input=10,foo.profdata \-weighted\-input=1,bar.profdata \-weighted\-input=1,baz.profdata \-output merged.profdata
+.ft P
+.fi
+.UNINDENT
+.UNINDENT
+.SH SHOW
+.SS SYNOPSIS
+.sp
+\fBllvm\-profdata show\fP [\fIoptions\fP] [\fIfilename\fP]
+.SS DESCRIPTION
+.sp
+\fBllvm\-profdata show\fP takes a profile data file and displays the
+information about the profile counters for this file and
+for any of the specified function(s).
+.sp
+If \fIfilename\fP is omitted or is \fB\-\fP, then \fBllvm\-profdata show\fP reads its
+input from standard input.
+.SS OPTIONS
+.INDENT 0.0
+.TP
+.B \-all\-functions
+Print details for every function.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-counts
+Print the counter values for the displayed functions.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-function=string
+Print details for a function if the function\(aqs name contains the given string.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-help
+Print a summary of command line options.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-output=output, \-o=output
+Specify the output file name.  If \fIoutput\fP is \fB\-\fP or it isn\(aqt specified,
+then the output is sent to standard output.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-instr (default)
+Specify that the input profile is an instrumentation\-based profile.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-text
+Instruct the profile dumper to show profile counts in the text format of the
+instrumentation\-based profile data representation. By default, the profile
+information is dumped in a more human readable form (also in text) with
+annotations.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-sample
+Specify that the input profile is a sample\-based profile.
+.UNINDENT
+.SH EXIT STATUS
+.sp
+\fBllvm\-profdata\fP returns 1 if the command is omitted or is invalid,
+if it cannot read input files, or if there is a mismatch between their data.
+.SH AUTHOR
+Maintained by The LLVM Team (http://llvm.org/).
+.SH COPYRIGHT
+2003-2016, LLVM Project
+.\" Generated by docutils manpage writer.
+.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/Solaris/man1/llvm-readobj.1	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,129 @@
+.\" Man page generated from reStructuredText.
+.
+.TH "LLVM-READOBJ" "1" "2016-07-10" "3.8" "LLVM"
+.SH NAME
+llvm-readobj \- LLVM Object Reader
+.
+.nr rst2man-indent-level 0
+.
+.de1 rstReportMargin
+\\$1 \\n[an-margin]
+level \\n[rst2man-indent-level]
+level margin: \\n[rst2man-indent\\n[rst2man-indent-level]]
+-
+\\n[rst2man-indent0]
+\\n[rst2man-indent1]
+\\n[rst2man-indent2]
+..
+.de1 INDENT
+.\" .rstReportMargin pre:
+. RS \\$1
+. nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin]
+. nr rst2man-indent-level +1
+.\" .rstReportMargin post:
+..
+.de UNINDENT
+. RE
+.\" indent \\n[an-margin]
+.\" old: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.nr rst2man-indent-level -1
+.\" new: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.in \\n[rst2man-indent\\n[rst2man-indent-level]]u
+..
+.SH SYNOPSIS
+.sp
+\fBllvm\-readobj\fP [\fIoptions\fP] [\fIinput...\fP]
+.SH DESCRIPTION
+.sp
+The \fBllvm\-readobj\fP tool displays low\-level format\-specific information
+about one or more object files. The tool and its output is primarily designed
+for use in FileCheck\-based tests.
+.SH OPTIONS
+.sp
+If \fBinput\fP is "\fB\-\fP" or omitted, \fBllvm\-readobj\fP reads from standard
+input. Otherwise, it will read from the specified \fBfilenames\fP\&.
+.INDENT 0.0
+.TP
+.B \-help
+Print a summary of command line options.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-version
+Display the version of this program
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-file\-headers, \-h
+Display file headers.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-sections, \-s
+Display all sections.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-section\-data, \-sd
+When used with \fB\-sections\fP, display section data for each section shown.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-section\-relocations, \-sr
+When used with \fB\-sections\fP, display relocations for each section shown.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-section\-symbols, \-st
+When used with \fB\-sections\fP, display symbols for each section shown.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-relocations, \-r
+Display the relocation entries in the file.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-symbols, \-t
+Display the symbol table.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-dyn\-symbols
+Display the dynamic symbol table (only for ELF object files).
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-unwind, \-u
+Display unwind information.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-expand\-relocs
+When used with \fB\-relocations\fP, display each relocation in an expanded
+multi\-line format.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-dynamic\-table
+Display the ELF .dynamic section table (only for ELF object files).
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-needed\-libs
+Display the needed libraries (only for ELF object files).
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-program\-headers
+Display the ELF program headers (only for ELF object files).
+.UNINDENT
+.SH EXIT STATUS
+.sp
+\fBllvm\-readobj\fP returns 0.
+.SH AUTHOR
+Maintained by The LLVM Team (http://llvm.org/).
+.SH COPYRIGHT
+2003-2016, LLVM Project
+.\" Generated by docutils manpage writer.
+.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/Solaris/man1/llvm-stress.1	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,64 @@
+.\" Man page generated from reStructuredText.
+.
+.TH "LLVM-STRESS" "1" "2016-07-10" "3.8" "LLVM"
+.SH NAME
+llvm-stress \- generate random .ll files
+.
+.nr rst2man-indent-level 0
+.
+.de1 rstReportMargin
+\\$1 \\n[an-margin]
+level \\n[rst2man-indent-level]
+level margin: \\n[rst2man-indent\\n[rst2man-indent-level]]
+-
+\\n[rst2man-indent0]
+\\n[rst2man-indent1]
+\\n[rst2man-indent2]
+..
+.de1 INDENT
+.\" .rstReportMargin pre:
+. RS \\$1
+. nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin]
+. nr rst2man-indent-level +1
+.\" .rstReportMargin post:
+..
+.de UNINDENT
+. RE
+.\" indent \\n[an-margin]
+.\" old: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.nr rst2man-indent-level -1
+.\" new: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.in \\n[rst2man-indent\\n[rst2man-indent-level]]u
+..
+.SH SYNOPSIS
+.sp
+\fBllvm\-stress\fP [\-size=filesize] [\-seed=initialseed] [\-o=outfile]
+.SH DESCRIPTION
+.sp
+The \fBllvm\-stress\fP tool is used to generate random \fB\&.ll\fP files that
+can be used to test different components of LLVM.
+.SH OPTIONS
+.INDENT 0.0
+.TP
+.B \-o filename
+Specify the output filename.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-size size
+Specify the size of the generated \fB\&.ll\fP file.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-seed seed
+Specify the seed to be used for the randomly generated instructions.
+.UNINDENT
+.SH EXIT STATUS
+.sp
+\fBllvm\-stress\fP returns 0.
+.SH AUTHOR
+Maintained by The LLVM Team (http://llvm.org/).
+.SH COPYRIGHT
+2003-2016, LLVM Project
+.\" Generated by docutils manpage writer.
+.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/Solaris/man1/llvm-symbolizer.1	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,162 @@
+.\" Man page generated from reStructuredText.
+.
+.TH "LLVM-SYMBOLIZER" "1" "2016-07-10" "3.8" "LLVM"
+.SH NAME
+llvm-symbolizer \- convert addresses into source code locations
+.
+.nr rst2man-indent-level 0
+.
+.de1 rstReportMargin
+\\$1 \\n[an-margin]
+level \\n[rst2man-indent-level]
+level margin: \\n[rst2man-indent\\n[rst2man-indent-level]]
+-
+\\n[rst2man-indent0]
+\\n[rst2man-indent1]
+\\n[rst2man-indent2]
+..
+.de1 INDENT
+.\" .rstReportMargin pre:
+. RS \\$1
+. nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin]
+. nr rst2man-indent-level +1
+.\" .rstReportMargin post:
+..
+.de UNINDENT
+. RE
+.\" indent \\n[an-margin]
+.\" old: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.nr rst2man-indent-level -1
+.\" new: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.in \\n[rst2man-indent\\n[rst2man-indent-level]]u
+..
+.SH SYNOPSIS
+.sp
+\fBllvm\-symbolizer\fP [options]
+.SH DESCRIPTION
+.sp
+\fBllvm\-symbolizer\fP reads object file names and addresses from standard
+input and prints corresponding source code locations to standard output.
+If object file is specified in command line, \fBllvm\-symbolizer\fP
+processes only addresses from standard input, the rest is output verbatim.
+This program uses debug info sections and symbol table in the object files.
+.SH EXAMPLE
+.INDENT 0.0
+.INDENT 3.5
+.sp
+.nf
+.ft C
+$ cat addr.txt
+a.out 0x4004f4
+/tmp/b.out 0x400528
+/tmp/c.so 0x710
+/tmp/mach_universal_binary:i386 0x1f84
+/tmp/mach_universal_binary:x86_64 0x100000f24
+$ llvm\-symbolizer < addr.txt
+main
+/tmp/a.cc:4
+
+f(int, int)
+/tmp/b.cc:11
+
+h_inlined_into_g
+/tmp/header.h:2
+g_inlined_into_f
+/tmp/header.h:7
+f_inlined_into_main
+/tmp/source.cc:3
+main
+/tmp/source.cc:8
+
+_main
+/tmp/source_i386.cc:8
+
+_main
+/tmp/source_x86_64.cc:8
+$ cat addr2.txt
+0x4004f4
+0x401000
+$ llvm\-symbolizer \-obj=a.out < addr2.txt
+main
+/tmp/a.cc:4
+
+foo(int)
+/tmp/a.cc:12
+$cat addr.txt
+0x40054d
+$llvm\-symbolizer \-inlining \-print\-address \-pretty\-print \-obj=addr.exe < addr.txt
+0x40054d: inc at /tmp/x.c:3:3
+ (inlined by) main at /tmp/x.c:9:0
+$llvm\-symbolizer \-inlining \-pretty\-print \-obj=addr.exe < addr.txt
+inc at /tmp/x.c:3:3
+ (inlined by) main at /tmp/x.c:9:0
+.ft P
+.fi
+.UNINDENT
+.UNINDENT
+.SH OPTIONS
+.INDENT 0.0
+.TP
+.B \-obj
+Path to object file to be symbolized.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-functions=[none|short|linkage]
+Specify the way function names are printed (omit function name,
+print short function name, or print full linkage name, respectively).
+Defaults to \fBlinkage\fP\&.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-use\-symbol\-table
+Prefer function names stored in symbol table to function names
+in debug info sections. Defaults to true.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-demangle
+Print demangled function names. Defaults to true.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-inlining
+If a source code location is in an inlined function, prints all the
+inlnied frames. Defaults to true.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-default\-arch
+If a binary contains object files for multiple architectures (e.g. it is a
+Mach\-O universal binary), symbolize the object file for a given architecture.
+You can also specify architecture by writing \fBbinary_name:arch_name\fP in the
+input (see example above). If architecture is not specified in either way,
+address will not be symbolized. Defaults to empty string.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-dsym\-hint=<path/to/file.dSYM>
+(Darwin\-only flag). If the debug info for a binary isn\(aqt present in the default
+location, look for the debug info at the .dSYM path provided via the
+\fB\-dsym\-hint\fP flag. This flag can be used multiple times.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-print\-address
+Print address before the source code location. Defaults to false.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-pretty\-print
+Print human readable output. If \fB\-inlining\fP is specified, enclosing scope is
+prefixed by (inlined by). Refer to listed examples.
+.UNINDENT
+.SH EXIT STATUS
+.sp
+\fBllvm\-symbolizer\fP returns 0. Other exit codes imply internal program error.
+.SH AUTHOR
+Maintained by The LLVM Team (http://llvm.org/).
+.SH COPYRIGHT
+2003-2016, LLVM Project
+.\" Generated by docutils manpage writer.
+.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/Solaris/man1/opt.1	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,169 @@
+.\" Man page generated from reStructuredText.
+.
+.TH "OPT" "1" "2016-07-10" "3.8" "LLVM"
+.SH NAME
+opt \- LLVM optimizer
+.
+.nr rst2man-indent-level 0
+.
+.de1 rstReportMargin
+\\$1 \\n[an-margin]
+level \\n[rst2man-indent-level]
+level margin: \\n[rst2man-indent\\n[rst2man-indent-level]]
+-
+\\n[rst2man-indent0]
+\\n[rst2man-indent1]
+\\n[rst2man-indent2]
+..
+.de1 INDENT
+.\" .rstReportMargin pre:
+. RS \\$1
+. nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin]
+. nr rst2man-indent-level +1
+.\" .rstReportMargin post:
+..
+.de UNINDENT
+. RE
+.\" indent \\n[an-margin]
+.\" old: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.nr rst2man-indent-level -1
+.\" new: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.in \\n[rst2man-indent\\n[rst2man-indent-level]]u
+..
+.SH SYNOPSIS
+.sp
+\fBopt\fP [\fIoptions\fP] [\fIfilename\fP]
+.SH DESCRIPTION
+.sp
+The \fBopt\fP 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 \fBopt\fP depends on whether the \fB\-analyze\fP option is
+given.
+.sp
+When \fB\-analyze\fP is specified, \fBopt\fP 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.
+.sp
+While \fB\-analyze\fP is \fInot\fP given, \fBopt\fP attempts to produce an
+optimized output file.  The optimizations available via \fBopt\fP depend
+upon what libraries were linked into it as well as any additional libraries
+that have been loaded with the \fI\%\-load\fP option.  Use the \fI\%\-help\fP
+option to determine what optimizations you can use.
+.sp
+If \fBfilename\fP is omitted from the command line or is "\fB\-\fP", \fBopt\fP
+reads its input from standard input.  Inputs can be in either the LLVM assembly
+language format (\fB\&.ll\fP) or the LLVM bitcode format (\fB\&.bc\fP).
+.sp
+If an output filename is not specified with the \fI\%\-o\fP option,
+\fBopt\fP writes its output to the standard output.
+.SH OPTIONS
+.INDENT 0.0
+.TP
+.B \-f
+Enable binary output on terminals.  Normally, \fBopt\fP will refuse to
+write raw bitcode output if the output stream is a terminal.  With this option,
+\fBopt\fP will write raw bitcode regardless of the output device.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-help
+Print a summary of command line options.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-o <filename>
+Specify the output filename.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-S
+Write output in LLVM intermediate language (instead of bitcode).
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-{passname}
+\fBopt\fP provides the ability to run any of LLVM\(aqs optimization or
+analysis passes in any order.  The \fI\%\-help\fP 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).
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-disable\-inlining
+This option simply removes the inlining pass from the standard list.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-disable\-opt
+This option is only meaningful when \fB\-std\-link\-opts\fP is given.  It
+disables most passes.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-strip\-debug
+This option causes opt to strip debug information from the module before
+applying other optimizations.  It is essentially the same as \fB\-strip\fP
+but it ensures that stripping of debug information is done first.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-verify\-each
+This option causes opt to add a verify pass after every pass otherwise
+specified on the command line (including \fB\-verify\fP).  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.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-stats
+Print statistics.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-time\-passes
+Record the amount of time needed for each pass and print it to standard
+error.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-debug
+If this is a debug build, this option will enable debug printouts from passes
+which use the \fBDEBUG()\fP macro.  See the \fI\%LLVM Programmer\(aqs Manual\fP, section \fB#DEBUG\fP for more information.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-load=<plugin>
+Load the dynamic object \fBplugin\fP\&.  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 \fI\%\-help\fP and \fI\%\-load\fP
+options together.  For example:
+.INDENT 7.0
+.INDENT 3.5
+.sp
+.nf
+.ft C
+opt \-load=plugin.so \-help
+.ft P
+.fi
+.UNINDENT
+.UNINDENT
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-p
+Print module after each transformation.
+.UNINDENT
+.SH EXIT STATUS
+.sp
+If \fBopt\fP succeeds, it will exit with 0.  Otherwise, if an error
+occurs, it will exit with a non\-zero value.
+.SH AUTHOR
+Maintained by The LLVM Team (http://llvm.org/).
+.SH COPYRIGHT
+2003-2016, LLVM Project
+.\" Generated by docutils manpage writer.
+.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/Solaris/man1/tblgen.1	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,181 @@
+.\" Man page generated from reStructuredText.
+.
+.TH "TBLGEN" "1" "2016-07-10" "3.8" "LLVM"
+.SH NAME
+tblgen \- Target Description To C++ Code Generator
+.
+.nr rst2man-indent-level 0
+.
+.de1 rstReportMargin
+\\$1 \\n[an-margin]
+level \\n[rst2man-indent-level]
+level margin: \\n[rst2man-indent\\n[rst2man-indent-level]]
+-
+\\n[rst2man-indent0]
+\\n[rst2man-indent1]
+\\n[rst2man-indent2]
+..
+.de1 INDENT
+.\" .rstReportMargin pre:
+. RS \\$1
+. nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin]
+. nr rst2man-indent-level +1
+.\" .rstReportMargin post:
+..
+.de UNINDENT
+. RE
+.\" indent \\n[an-margin]
+.\" old: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.nr rst2man-indent-level -1
+.\" new: \\n[rst2man-indent\\n[rst2man-indent-level]]
+.in \\n[rst2man-indent\\n[rst2man-indent-level]]u
+..
+.SH SYNOPSIS
+.sp
+\fBtblgen\fP [\fIoptions\fP] [\fIfilename\fP]
+.SH DESCRIPTION
+.sp
+\fBtblgen\fP translates from target description (\fB\&.td\fP) 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.
+.sp
+The input and output of \fBtblgen\fP is beyond the scope of this short
+introduction; please see the introduction to TableGen\&.
+.sp
+The \fIfilename\fP argument specifies the name of a Target Description (\fB\&.td\fP)
+file to read as input.
+.SH OPTIONS
+.INDENT 0.0
+.TP
+.B \-help
+Print a summary of command line options.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-o filename
+Specify the output file name.  If \fBfilename\fP is \fB\-\fP, then
+\fBtblgen\fP sends its output to standard output.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-I directory
+Specify where to find other target description files for inclusion.  The
+\fBdirectory\fP value should be a full or partial path to a directory that
+contains target description files.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-asmparsernum N
+Make \-gen\-asm\-parser emit assembly writer number \fBN\fP\&.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-asmwriternum N
+Make \-gen\-asm\-writer emit assembly writer number \fBN\fP\&.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-class className
+Print the enumeration list for this class.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-print\-records
+Print all records to standard output (default).
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-print\-enums
+Print enumeration values for a class.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-print\-sets
+Print expanded sets for testing DAG exprs.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-gen\-emitter
+Generate machine code emitter.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-gen\-register\-info
+Generate registers and register classes info.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-gen\-instr\-info
+Generate instruction descriptions.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-gen\-asm\-writer
+Generate the assembly writer.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-gen\-disassembler
+Generate disassembler.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-gen\-pseudo\-lowering
+Generate pseudo instruction lowering.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-gen\-dag\-isel
+Generate a DAG (Directed Acycle Graph) instruction selector.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-gen\-asm\-matcher
+Generate assembly instruction matcher.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-gen\-dfa\-packetizer
+Generate DFA Packetizer for VLIW targets.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-gen\-fast\-isel
+Generate a "fast" instruction selector.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-gen\-subtarget
+Generate subtarget enumerations.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-gen\-intrinsic
+Generate intrinsic information.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-gen\-tgt\-intrinsic
+Generate target intrinsic information.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-gen\-enhanced\-disassembly\-info
+Generate enhanced disassembly info.
+.UNINDENT
+.INDENT 0.0
+.TP
+.B \-version
+Show the version number of this program.
+.UNINDENT
+.SH EXIT STATUS
+.sp
+If \fBtblgen\fP succeeds, it will exit with 0.  Otherwise, if an error
+occurs, it will exit with a non\-zero value.
+.SH AUTHOR
+Maintained by The LLVM Team (http://llvm.org/).
+.SH COPYRIGHT
+2003-2016, LLVM Project
+.\" Generated by docutils manpage writer.
+.
--- a/components/llvm/clang-build.p5m	Thu Jul 28 16:15:45 2016 -0700
+++ b/components/llvm/clang-build.p5m	Thu Jul 28 16:25:34 2016 -0700
@@ -38,10 +38,6 @@
 set name=info.upstream-url value=$(COMPONENT_PROJECT_URL)
 set name=org.opensolaris.arc-caseid value=PSARC/2013/188
 set name=org.opensolaris.consolidation value=$(CONSOLIDATION)
-file path=usr/bin/arcmt-test
-file path=usr/bin/c-arcmt-test
-file path=usr/bin/c-index-test
-file path=usr/bin/diagtool
 file path=usr/include/clang-c/BuildSystem.h
 file path=usr/include/clang-c/CXCompilationDatabase.h
 file path=usr/include/clang-c/CXErrorCode.h
@@ -49,7 +45,6 @@
 file path=usr/include/clang-c/Documentation.h
 file path=usr/include/clang-c/Index.h
 file path=usr/include/clang-c/Platform.h
-file path=usr/include/clang-c/module.modulemap
 file path=usr/include/clang/ARCMigrate/ARCMT.h
 file path=usr/include/clang/ARCMigrate/ARCMTActions.h
 file path=usr/include/clang/ARCMigrate/FileRemapper.h
@@ -90,7 +85,6 @@
 file path=usr/include/clang/AST/CommentParser.h
 file path=usr/include/clang/AST/CommentSema.h
 file path=usr/include/clang/AST/CommentVisitor.h
-file path=usr/include/clang/AST/DataRecursiveASTVisitor.h
 file path=usr/include/clang/AST/Decl.h
 file path=usr/include/clang/AST/DeclAccessPair.h
 file path=usr/include/clang/AST/DeclBase.h
@@ -110,6 +104,7 @@
 file path=usr/include/clang/AST/Expr.h
 file path=usr/include/clang/AST/ExprCXX.h
 file path=usr/include/clang/AST/ExprObjC.h
+file path=usr/include/clang/AST/ExprOpenMP.h
 file path=usr/include/clang/AST/ExternalASTSource.h
 file path=usr/include/clang/AST/GlobalDecl.h
 file path=usr/include/clang/AST/LambdaCapture.h
@@ -191,6 +186,7 @@
 file path=usr/include/clang/Basic/Builtins.def
 file path=usr/include/clang/Basic/Builtins.h
 file path=usr/include/clang/Basic/BuiltinsAArch64.def
+file path=usr/include/clang/Basic/BuiltinsAMDGPU.def
 file path=usr/include/clang/Basic/BuiltinsARM.def
 file path=usr/include/clang/Basic/BuiltinsHexagon.def
 file path=usr/include/clang/Basic/BuiltinsLe64.def
@@ -198,7 +194,8 @@
 file path=usr/include/clang/Basic/BuiltinsNEON.def
 file path=usr/include/clang/Basic/BuiltinsNVPTX.def
 file path=usr/include/clang/Basic/BuiltinsPPC.def
-file path=usr/include/clang/Basic/BuiltinsR600.def
+file path=usr/include/clang/Basic/BuiltinsSystemZ.def
+file path=usr/include/clang/Basic/BuiltinsWebAssembly.def
 file path=usr/include/clang/Basic/BuiltinsX86.def
 file path=usr/include/clang/Basic/BuiltinsXCore.def
 file path=usr/include/clang/Basic/CapturedStmt.h
@@ -270,6 +267,7 @@
 file path=usr/include/clang/CodeGen/CodeGenABITypes.h
 file path=usr/include/clang/CodeGen/CodeGenAction.h
 file path=usr/include/clang/CodeGen/ModuleBuilder.h
+file path=usr/include/clang/CodeGen/ObjectFilePCHContainerOperations.h
 file path=usr/include/clang/Config/config.h
 file path=usr/include/clang/Driver/Action.h
 file path=usr/include/clang/Driver/Compilation.h
@@ -313,6 +311,7 @@
 file path=usr/include/clang/Frontend/LogDiagnosticPrinter.h
 file path=usr/include/clang/Frontend/MigratorOptions.h
 file path=usr/include/clang/Frontend/MultiplexConsumer.h
+file path=usr/include/clang/Frontend/PCHContainerOperations.h
 file path=usr/include/clang/Frontend/PreprocessorOutputOptions.h
 file path=usr/include/clang/Frontend/SerializedDiagnosticPrinter.h
 file path=usr/include/clang/Frontend/SerializedDiagnosticReader.h
@@ -358,6 +357,7 @@
 file path=usr/include/clang/Parse/Parser.h
 file path=usr/include/clang/Rewrite/Core/DeltaTree.h
 file path=usr/include/clang/Rewrite/Core/HTMLRewrite.h
+file path=usr/include/clang/Rewrite/Core/RewriteBuffer.h
 file path=usr/include/clang/Rewrite/Core/RewriteRope.h
 file path=usr/include/clang/Rewrite/Core/Rewriter.h
 file path=usr/include/clang/Rewrite/Core/TokenRewriter.h
@@ -411,6 +411,7 @@
 file path=usr/include/clang/Serialization/ContinuousRangeMap.h
 file path=usr/include/clang/Serialization/GlobalModuleIndex.h
 file path=usr/include/clang/Serialization/Module.h
+file path=usr/include/clang/Serialization/ModuleFileExtension.h
 file path=usr/include/clang/Serialization/ModuleManager.h
 file path=usr/include/clang/Serialization/SerializationDiagnostic.h
 file path=usr/include/clang/StaticAnalyzer/Checkers/ClangCheckers.h
@@ -427,6 +428,7 @@
 file path=usr/include/clang/StaticAnalyzer/Core/CheckerManager.h
 file path=usr/include/clang/StaticAnalyzer/Core/CheckerOptInfo.h
 file path=usr/include/clang/StaticAnalyzer/Core/CheckerRegistry.h
+file path=usr/include/clang/StaticAnalyzer/Core/IssueHash.h
 file path=usr/include/clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h
 file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h
 file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h
@@ -438,10 +440,12 @@
 file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
 file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
 file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeInfo.h
+file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeMap.h
 file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/Environment.h
 file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h
 file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
 file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/FunctionSummary.h
+file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/LoopWidening.h
 file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h
 file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
 file path=usr/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h
@@ -464,6 +468,7 @@
 file path=usr/include/clang/Tooling/CommonOptionsParser.h
 file path=usr/include/clang/Tooling/CompilationDatabase.h
 file path=usr/include/clang/Tooling/CompilationDatabasePluginRegistry.h
+file path=usr/include/clang/Tooling/Core/Lookup.h
 file path=usr/include/clang/Tooling/Core/Replacement.h
 file path=usr/include/clang/Tooling/FileMatchTrie.h
 file path=usr/include/clang/Tooling/JSONCompilationDatabase.h
@@ -471,7 +476,6 @@
 file path=usr/include/clang/Tooling/RefactoringCallbacks.h
 file path=usr/include/clang/Tooling/ReplacementsYaml.h
 file path=usr/include/clang/Tooling/Tooling.h
-file path=usr/lib/$(MACH64)/libclang.a
 file path=usr/lib/$(MACH64)/libclangARCMigrate.a
 file path=usr/lib/$(MACH64)/libclangAST.a
 file path=usr/lib/$(MACH64)/libclangASTMatchers.a
@@ -496,6 +500,11 @@
 file path=usr/lib/$(MACH64)/libclangStaticAnalyzerFrontend.a
 file path=usr/lib/$(MACH64)/libclangTooling.a
 file path=usr/lib/$(MACH64)/libclangToolingCore.a
+#
+file path=usr/share/clang/cmake/ClangConfig.cmake
+file path=usr/share/clang/cmake/ClangTargets-release.cmake
+file path=usr/share/clang/cmake/ClangTargets.cmake
+#
 license llvm.license license="University of Illinois/NCSA"
 depend type=require fmri=pkg:/developer/llvm/llvm-build
 
--- a/components/llvm/clang.p5m	Thu Jul 28 16:15:45 2016 -0700
+++ b/components/llvm/clang.p5m	Thu Jul 28 16:25:34 2016 -0700
@@ -23,6 +23,7 @@
 # Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
 #
 
+<transform file path=usr.*/man/.+ -> default mangler.man.stability uncommitted>
 set name=pkg.fmri \
     value=pkg:/developer/llvm/clang@$(IPS_COMPONENT_VERSION),$(BUILD_VERSION)
 set name=pkg.summary \
@@ -38,13 +39,22 @@
 set name=info.upstream-url value=$(COMPONENT_PROJECT_URL)
 set name=org.opensolaris.arc-caseid value=PSARC/2013/188
 set name=org.opensolaris.consolidation value=$(CONSOLIDATION)
-file path=usr/bin/clang
-hardlink path=usr/bin/clang++ target=clang
-file path=usr/bin/clang-check
-file path=usr/bin/clang-format
-file path=usr/bin/clang-tblgen
+file usr/bin/$(MACH64)/arcmt-test path=usr/bin/arcmt-test
+file usr/bin/$(MACH64)/c-arcmt-test path=usr/bin/c-arcmt-test
+file usr/bin/$(MACH64)/c-index-test path=usr/bin/c-index-test
+hardlink path=usr/bin/clang target=clang-3.8
+hardlink path=usr/bin/clang++ target=clang-3.8
+file usr/bin/$(MACH64)/clang-3.8 path=usr/bin/clang-3.8
+file usr/bin/$(MACH64)/clang-format path=usr/bin/clang-format
+file usr/bin/$(MACH64)/diagtool path=usr/bin/diagtool
+file usr/bin/$(MACH64)/git-clang-format path=usr/bin/git-clang-format
+file usr/bin/$(MACH64)/scan-build path=usr/bin/scan-build
+file usr/bin/$(MACH64)/scan-view path=usr/bin/scan-view
 file path=usr/lib/$(MACH64)/libclang.so
+file usr/libexec/$(MACH64)/c++-analyzer path=usr/lib/c++-analyzer
+file usr/libexec/$(MACH64)/ccc-analyzer path=usr/lib/ccc-analyzer
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/Intrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/__clang_cuda_runtime_wrapper.h
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/__stddef_max_align_t.h
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/__wmmintrin_aes.h
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/__wmmintrin_pclmul.h
@@ -55,21 +65,29 @@
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/arm_neon.h
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/avx2intrin.h
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/avx512bwintrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/avx512cdintrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/avx512dqintrin.h
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/avx512erintrin.h
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/avx512fintrin.h
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/avx512vlbwintrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/avx512vldqintrin.h
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/avx512vlintrin.h
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/avxintrin.h
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/bmi2intrin.h
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/bmiintrin.h
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/cpuid.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/cuda_builtin_vars.h
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/emmintrin.h
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/f16cintrin.h
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/float.h
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/fma4intrin.h
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/fmaintrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/fxsrintrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/htmintrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/htmxlintrin.h
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/ia32intrin.h
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/immintrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/inttypes.h
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/iso646.h
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/limits.h
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/lzcntintrin.h
@@ -78,11 +96,13 @@
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/mmintrin.h
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/module.modulemap
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/nmmintrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/pkuintrin.h
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/pmmintrin.h
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/popcntintrin.h
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/prfchwintrin.h
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/rdseedintrin.h
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/rtmintrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/s390intrin.h
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/shaintrin.h
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/smmintrin.h
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/stdalign.h
@@ -98,10 +118,33 @@
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/unwind.h
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/vadefs.h
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/varargs.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/vecintrin.h
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/wmmintrin.h
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/x86intrin.h
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/xmmintrin.h
 file path=usr/lib/clang/$(COMPONENT_VERSION)/include/xopintrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/xsavecintrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/xsaveintrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/xsaveoptintrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/xsavesintrin.h
+file path=usr/lib/clang/$(COMPONENT_VERSION)/include/xtestintrin.h
+$(SOLARIS_11_ONLY)file path=usr/lib/clang/$(MACH64)/cxa_finalize.o
+$(SOLARIS_11_ONLY)file path=usr/lib/clang/$(MACH64)/cxa_finalize_pic.o
+$(SOLARIS_11_ONLY)file path=usr/lib/clang/cxa_finalize.o
+$(SOLARIS_11_ONLY)file path=usr/lib/clang/cxa_finalize_pic.o
+file path=usr/lib/python2.7/vendor-packages/Reporter.py
+file path=usr/lib/python2.7/vendor-packages/ScanView.py
+file path=usr/lib/python2.7/vendor-packages/clang-format-diff.py
+file path=usr/lib/python2.7/vendor-packages/clang-format-sublime.py
+file path=usr/lib/python2.7/vendor-packages/clang-format.py
+file path=usr/share/clang/clang-format-bbedit.applescript
+file path=usr/share/clang/clang-format.el
+file path=usr/share/man/man1/clang.1
+file path=usr/share/scan-build/scanview.css
+file path=usr/share/scan-build/sorttable.js
+file path=usr/share/scan-view/FileRadar.scpt
+file path=usr/share/scan-view/GetRadarVersion.scpt
+file path=usr/share/scan-view/bugcatcher.ico
 license llvm.license license="University of Illinois/NCSA"
 depend type=require fmri=pkg:/system/header
 
--- a/components/llvm/cxa_finalize/Makefile	Thu Jul 28 16:15:45 2016 -0700
+++ b/components/llvm/cxa_finalize/Makefile	Thu Jul 28 16:25:34 2016 -0700
@@ -22,12 +22,10 @@
 #
 # Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
 #
+export PARFAIT_BUILD=no
 COMPILER= gcc
-include ../../../make-rules/shared-macros.mk
 
-include $(WS_MAKE_RULES)/prep.mk
-include $(WS_MAKE_RULES)/configure.mk
-include $(WS_MAKE_RULES)/ips.mk
+include ../../../make-rules/shared-macros.mk
 
 COMPONENT_DIR := $(shell pwd)/..
 
@@ -38,10 +36,17 @@
 OBJECTS = cxa_finalize-32.o cxa_finalize-64.o \
 	  cxa_finalize_pic-32.o cxa_finalize_pic-64.o
 
-include $(WS_MAKE_RULES)/prep.mk
+include $(WS_MAKE_RULES)/common.mk
+
+GCC_VERSION := 4.9
+
+# We need GCC version 4.9, and not another version.
+CC=/usr/gcc/$(GCC_VERSION)/bin/gcc
+CXX=/usr/gcc/$(GCC_VERSION)/bin/g++
 
 RELEASE_LIST=Debug+Asserts+Checks Debug+Asserts Debug Release+Debug Release Unoptimized
 
+# Keep CFLAGS simple and generic.
 CFLAGS = -g -O2 -std=c99 -Wall -Wextra -Wcast-align
 ARCH = $(shell uname -p)
 
@@ -50,7 +55,7 @@
 endif
 
 ifeq ($(ARCH),i386)
-  CFLAGS += -mtune=opteron -march=opteron
+  CFLAGS += -mtune=opteron -march=opteron -mno-sse3 -mno-ssse3
 endif
 
 all:: $(OBJECTS)
--- a/components/llvm/llvm-build.p5m	Thu Jul 28 16:15:45 2016 -0700
+++ b/components/llvm/llvm-build.p5m	Thu Jul 28 16:25:34 2016 -0700
@@ -43,12 +43,14 @@
 file path=usr/include/llvm-c/BitWriter.h
 file path=usr/include/llvm-c/Core.h
 file path=usr/include/llvm-c/Disassembler.h
+file path=usr/include/llvm-c/ErrorHandling.h
 file path=usr/include/llvm-c/ExecutionEngine.h
 file path=usr/include/llvm-c/IRReader.h
 file path=usr/include/llvm-c/Initialization.h
 file path=usr/include/llvm-c/LinkTimeOptimizer.h
 file path=usr/include/llvm-c/Linker.h
 file path=usr/include/llvm-c/Object.h
+file path=usr/include/llvm-c/OrcBindings.h
 file path=usr/include/llvm-c/Support.h
 file path=usr/include/llvm-c/Target.h
 file path=usr/include/llvm-c/TargetMachine.h
@@ -56,6 +58,7 @@
 file path=usr/include/llvm-c/Transforms/PassManagerBuilder.h
 file path=usr/include/llvm-c/Transforms/Scalar.h
 file path=usr/include/llvm-c/Transforms/Vectorize.h
+file path=usr/include/llvm-c/Types.h
 file path=usr/include/llvm-c/lto.h
 file path=usr/include/llvm/ADT/APFloat.h
 file path=usr/include/llvm/ADT/APInt.h
@@ -68,6 +71,7 @@
 file path=usr/include/llvm/ADT/DenseMapInfo.h
 file path=usr/include/llvm/ADT/DenseSet.h
 file path=usr/include/llvm/ADT/DepthFirstIterator.h
+file path=usr/include/llvm/ADT/EpochTracker.h
 file path=usr/include/llvm/ADT/EquivalenceClasses.h
 file path=usr/include/llvm/ADT/FoldingSet.h
 file path=usr/include/llvm/ADT/GraphTraits.h
@@ -83,7 +87,9 @@
 file path=usr/include/llvm/ADT/None.h
 file path=usr/include/llvm/ADT/Optional.h
 file path=usr/include/llvm/ADT/PackedVector.h
+file path=usr/include/llvm/ADT/PointerEmbeddedInt.h
 file path=usr/include/llvm/ADT/PointerIntPair.h
+file path=usr/include/llvm/ADT/PointerSumType.h
 file path=usr/include/llvm/ADT/PointerUnion.h
 file path=usr/include/llvm/ADT/PostOrderIterator.h
 file path=usr/include/llvm/ADT/PriorityQueue.h
@@ -119,11 +125,13 @@
 file path=usr/include/llvm/Analysis/AliasAnalysis.h
 file path=usr/include/llvm/Analysis/AliasSetTracker.h
 file path=usr/include/llvm/Analysis/AssumptionCache.h
+file path=usr/include/llvm/Analysis/BasicAliasAnalysis.h
 file path=usr/include/llvm/Analysis/BlockFrequencyInfo.h
 file path=usr/include/llvm/Analysis/BlockFrequencyInfoImpl.h
 file path=usr/include/llvm/Analysis/BranchProbabilityInfo.h
 file path=usr/include/llvm/Analysis/CFG.h
 file path=usr/include/llvm/Analysis/CFGPrinter.h
+file path=usr/include/llvm/Analysis/CFLAliasAnalysis.h
 file path=usr/include/llvm/Analysis/CGSCCPassManager.h
 file path=usr/include/llvm/Analysis/CallGraph.h
 file path=usr/include/llvm/Analysis/CallGraphSCCPass.h
@@ -131,32 +139,38 @@
 file path=usr/include/llvm/Analysis/CaptureTracking.h
 file path=usr/include/llvm/Analysis/CodeMetrics.h
 file path=usr/include/llvm/Analysis/ConstantFolding.h
-file path=usr/include/llvm/Analysis/ConstantsScanner.h
 file path=usr/include/llvm/Analysis/DOTGraphTraitsPass.h
+file path=usr/include/llvm/Analysis/DemandedBits.h
 file path=usr/include/llvm/Analysis/DependenceAnalysis.h
+file path=usr/include/llvm/Analysis/DivergenceAnalysis.h
 file path=usr/include/llvm/Analysis/DomPrinter.h
 file path=usr/include/llvm/Analysis/DominanceFrontier.h
 file path=usr/include/llvm/Analysis/DominanceFrontierImpl.h
-file path=usr/include/llvm/Analysis/FunctionTargetTransformInfo.h
+file path=usr/include/llvm/Analysis/EHPersonalities.h
+file path=usr/include/llvm/Analysis/GlobalsModRef.h
 file path=usr/include/llvm/Analysis/IVUsers.h
 file path=usr/include/llvm/Analysis/InlineCost.h
 file path=usr/include/llvm/Analysis/InstructionSimplify.h
 file path=usr/include/llvm/Analysis/Interval.h
 file path=usr/include/llvm/Analysis/IntervalIterator.h
 file path=usr/include/llvm/Analysis/IntervalPartition.h
-file path=usr/include/llvm/Analysis/JumpInstrTableInfo.h
+file path=usr/include/llvm/Analysis/IteratedDominanceFrontier.h
 file path=usr/include/llvm/Analysis/LazyCallGraph.h
 file path=usr/include/llvm/Analysis/LazyValueInfo.h
-file path=usr/include/llvm/Analysis/LibCallAliasAnalysis.h
-file path=usr/include/llvm/Analysis/LibCallSemantics.h
 file path=usr/include/llvm/Analysis/Lint.h
 file path=usr/include/llvm/Analysis/Loads.h
+file path=usr/include/llvm/Analysis/LoopAccessAnalysis.h
 file path=usr/include/llvm/Analysis/LoopInfo.h
 file path=usr/include/llvm/Analysis/LoopInfoImpl.h
 file path=usr/include/llvm/Analysis/LoopIterator.h
 file path=usr/include/llvm/Analysis/LoopPass.h
 file path=usr/include/llvm/Analysis/MemoryBuiltins.h
 file path=usr/include/llvm/Analysis/MemoryDependenceAnalysis.h
+file path=usr/include/llvm/Analysis/MemoryLocation.h
+file path=usr/include/llvm/Analysis/ObjCARCAliasAnalysis.h
+file path=usr/include/llvm/Analysis/ObjCARCAnalysisUtils.h
+file path=usr/include/llvm/Analysis/ObjCARCInstKind.h
+file path=usr/include/llvm/Analysis/OrderedBasicBlock.h
 file path=usr/include/llvm/Analysis/PHITransAddr.h
 file path=usr/include/llvm/Analysis/Passes.h
 file path=usr/include/llvm/Analysis/PostDominators.h
@@ -167,15 +181,23 @@
 file path=usr/include/llvm/Analysis/RegionPass.h
 file path=usr/include/llvm/Analysis/RegionPrinter.h
 file path=usr/include/llvm/Analysis/ScalarEvolution.h
+file path=usr/include/llvm/Analysis/ScalarEvolutionAliasAnalysis.h
 file path=usr/include/llvm/Analysis/ScalarEvolutionExpander.h
 file path=usr/include/llvm/Analysis/ScalarEvolutionExpressions.h
 file path=usr/include/llvm/Analysis/ScalarEvolutionNormalization.h
+file path=usr/include/llvm/Analysis/ScopedNoAliasAA.h
 file path=usr/include/llvm/Analysis/SparsePropagation.h
 file path=usr/include/llvm/Analysis/TargetFolder.h
+file path=usr/include/llvm/Analysis/TargetLibraryInfo.def
+file path=usr/include/llvm/Analysis/TargetLibraryInfo.h
 file path=usr/include/llvm/Analysis/TargetTransformInfo.h
+file path=usr/include/llvm/Analysis/TargetTransformInfoImpl.h
 file path=usr/include/llvm/Analysis/Trace.h
+file path=usr/include/llvm/Analysis/TypeBasedAliasAnalysis.h
 file path=usr/include/llvm/Analysis/ValueTracking.h
+file path=usr/include/llvm/Analysis/VectorUtils.h
 file path=usr/include/llvm/AsmParser/Parser.h
+file path=usr/include/llvm/AsmParser/SlotMapping.h
 file path=usr/include/llvm/Bitcode/BitCodes.h
 file path=usr/include/llvm/Bitcode/BitcodeWriterPass.h
 file path=usr/include/llvm/Bitcode/BitstreamReader.h
@@ -184,15 +206,19 @@
 file path=usr/include/llvm/Bitcode/ReaderWriter.h
 file path=usr/include/llvm/CodeGen/Analysis.h
 file path=usr/include/llvm/CodeGen/AsmPrinter.h
+file path=usr/include/llvm/CodeGen/AtomicExpandUtils.h
+file path=usr/include/llvm/CodeGen/BasicTTIImpl.h
 file path=usr/include/llvm/CodeGen/CalcSpillWeights.h
 file path=usr/include/llvm/CodeGen/CallingConvLower.h
 file path=usr/include/llvm/CodeGen/CommandFlags.h
 file path=usr/include/llvm/CodeGen/DAGCombine.h
 file path=usr/include/llvm/CodeGen/DFAPacketizer.h
 file path=usr/include/llvm/CodeGen/DIE.h
+file path=usr/include/llvm/CodeGen/DIEValue.def
+file path=usr/include/llvm/CodeGen/DwarfStringPoolEntry.h
 file path=usr/include/llvm/CodeGen/EdgeBundles.h
 file path=usr/include/llvm/CodeGen/FastISel.h
-file path=usr/include/llvm/CodeGen/ForwardControlFlowIntegrity.h
+file path=usr/include/llvm/CodeGen/FaultMaps.h
 file path=usr/include/llvm/CodeGen/FunctionLoweringInfo.h
 file path=usr/include/llvm/CodeGen/GCMetadata.h
 file path=usr/include/llvm/CodeGen/GCMetadataPrinter.h
@@ -200,7 +226,6 @@
 file path=usr/include/llvm/CodeGen/GCs.h
 file path=usr/include/llvm/CodeGen/ISDOpcodes.h
 file path=usr/include/llvm/CodeGen/IntrinsicLowering.h
-file path=usr/include/llvm/CodeGen/JumpInstrTables.h
 file path=usr/include/llvm/CodeGen/LatencyPriorityQueue.h
 file path=usr/include/llvm/CodeGen/LexicalScopes.h
 file path=usr/include/llvm/CodeGen/LinkAllAsmWriterComponents.h
@@ -213,6 +238,8 @@
 file path=usr/include/llvm/CodeGen/LiveRegMatrix.h
 file path=usr/include/llvm/CodeGen/LiveStackAnalysis.h
 file path=usr/include/llvm/CodeGen/LiveVariables.h
+file path=usr/include/llvm/CodeGen/MIRParser/MIRParser.h
+file path=usr/include/llvm/CodeGen/MIRYamlMapping.h
 file path=usr/include/llvm/CodeGen/MachORelocation.h
 file path=usr/include/llvm/CodeGen/MachineBasicBlock.h
 file path=usr/include/llvm/CodeGen/MachineBlockFrequencyInfo.h
@@ -224,6 +251,7 @@
 file path=usr/include/llvm/CodeGen/MachineFrameInfo.h
 file path=usr/include/llvm/CodeGen/MachineFunction.h
 file path=usr/include/llvm/CodeGen/MachineFunctionAnalysis.h
+file path=usr/include/llvm/CodeGen/MachineFunctionInitializer.h
 file path=usr/include/llvm/CodeGen/MachineFunctionPass.h
 file path=usr/include/llvm/CodeGen/MachineInstr.h
 file path=usr/include/llvm/CodeGen/MachineInstrBuilder.h
@@ -248,6 +276,7 @@
 file path=usr/include/llvm/CodeGen/PBQP/ReductionRules.h
 file path=usr/include/llvm/CodeGen/PBQP/Solution.h
 file path=usr/include/llvm/CodeGen/PBQPRAConstraint.h
+file path=usr/include/llvm/CodeGen/ParallelCG.h
 file path=usr/include/llvm/CodeGen/Passes.h
 file path=usr/include/llvm/CodeGen/PseudoSourceValue.h
 file path=usr/include/llvm/CodeGen/RegAllocPBQP.h
@@ -267,7 +296,6 @@
 file path=usr/include/llvm/CodeGen/SelectionDAGISel.h
 file path=usr/include/llvm/CodeGen/SelectionDAGNodes.h
 file path=usr/include/llvm/CodeGen/SlotIndexes.h
-file path=usr/include/llvm/CodeGen/StackMapLivenessAnalysis.h
 file path=usr/include/llvm/CodeGen/StackMaps.h
 file path=usr/include/llvm/CodeGen/StackProtector.h
 file path=usr/include/llvm/CodeGen/TargetLoweringObjectFileImpl.h
@@ -275,37 +303,133 @@
 file path=usr/include/llvm/CodeGen/ValueTypes.h
 file path=usr/include/llvm/CodeGen/ValueTypes.td
 file path=usr/include/llvm/CodeGen/VirtRegMap.h
+file path=usr/include/llvm/CodeGen/WinEHFuncInfo.h
 file path=usr/include/llvm/Config/AsmParsers.def
 file path=usr/include/llvm/Config/AsmPrinters.def
 file path=usr/include/llvm/Config/Disassemblers.def
 file path=usr/include/llvm/Config/Targets.def
-file path=usr/include/llvm/Config/config.h
 file path=usr/include/llvm/Config/llvm-config.h
+file path=usr/include/llvm/DebugInfo/CodeView/CodeView.h
+file path=usr/include/llvm/DebugInfo/CodeView/CodeViewOStream.h
+file path=usr/include/llvm/DebugInfo/CodeView/FieldListRecordBuilder.h
+file path=usr/include/llvm/DebugInfo/CodeView/FunctionId.h
+file path=usr/include/llvm/DebugInfo/CodeView/Line.h
+file path=usr/include/llvm/DebugInfo/CodeView/ListRecordBuilder.h
+file path=usr/include/llvm/DebugInfo/CodeView/MemoryTypeTableBuilder.h
+file path=usr/include/llvm/DebugInfo/CodeView/MethodListRecordBuilder.h
+file path=usr/include/llvm/DebugInfo/CodeView/TypeIndex.h
+file path=usr/include/llvm/DebugInfo/CodeView/TypeRecord.h
+file path=usr/include/llvm/DebugInfo/CodeView/TypeRecordBuilder.h
+file path=usr/include/llvm/DebugInfo/CodeView/TypeSymbolEmitter.h
+file path=usr/include/llvm/DebugInfo/CodeView/TypeTableBuilder.h
 file path=usr/include/llvm/DebugInfo/DIContext.h
-file path=usr/include/llvm/DebugInfo/DWARFAbbreviationDeclaration.h
-file path=usr/include/llvm/DebugInfo/DWARFAcceleratorTable.h
-file path=usr/include/llvm/DebugInfo/DWARFCompileUnit.h
-file path=usr/include/llvm/DebugInfo/DWARFContext.h
-file path=usr/include/llvm/DebugInfo/DWARFDebugAbbrev.h
-file path=usr/include/llvm/DebugInfo/DWARFDebugArangeSet.h
-file path=usr/include/llvm/DebugInfo/DWARFDebugAranges.h
-file path=usr/include/llvm/DebugInfo/DWARFDebugFrame.h
-file path=usr/include/llvm/DebugInfo/DWARFDebugInfoEntry.h
-file path=usr/include/llvm/DebugInfo/DWARFDebugLine.h
-file path=usr/include/llvm/DebugInfo/DWARFDebugLoc.h
-file path=usr/include/llvm/DebugInfo/DWARFDebugRangeList.h
-file path=usr/include/llvm/DebugInfo/DWARFFormValue.h
-file path=usr/include/llvm/DebugInfo/DWARFRelocMap.h
-file path=usr/include/llvm/DebugInfo/DWARFSection.h
-file path=usr/include/llvm/DebugInfo/DWARFTypeUnit.h
-file path=usr/include/llvm/DebugInfo/DWARFUnit.h
+file path=usr/include/llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h
+file path=usr/include/llvm/DebugInfo/DWARF/DWARFAcceleratorTable.h
+file path=usr/include/llvm/DebugInfo/DWARF/DWARFCompileUnit.h
+file path=usr/include/llvm/DebugInfo/DWARF/DWARFContext.h
+file path=usr/include/llvm/DebugInfo/DWARF/DWARFDebugAbbrev.h
+file path=usr/include/llvm/DebugInfo/DWARF/DWARFDebugArangeSet.h
+file path=usr/include/llvm/DebugInfo/DWARF/DWARFDebugAranges.h
+file path=usr/include/llvm/DebugInfo/DWARF/DWARFDebugFrame.h
+file path=usr/include/llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h
+file path=usr/include/llvm/DebugInfo/DWARF/DWARFDebugLine.h
+file path=usr/include/llvm/DebugInfo/DWARF/DWARFDebugLoc.h
+file path=usr/include/llvm/DebugInfo/DWARF/DWARFDebugMacro.h
+file path=usr/include/llvm/DebugInfo/DWARF/DWARFDebugRangeList.h
+file path=usr/include/llvm/DebugInfo/DWARF/DWARFFormValue.h
+file path=usr/include/llvm/DebugInfo/DWARF/DWARFRelocMap.h
+file path=usr/include/llvm/DebugInfo/DWARF/DWARFSection.h
+file path=usr/include/llvm/DebugInfo/DWARF/DWARFTypeUnit.h
+file path=usr/include/llvm/DebugInfo/DWARF/DWARFUnit.h
+file path=usr/include/llvm/DebugInfo/DWARF/DWARFUnitIndex.h
+file path=usr/include/llvm/DebugInfo/PDB/ConcreteSymbolEnumerator.h
+file path=usr/include/llvm/DebugInfo/PDB/DIA/DIADataStream.h
+file path=usr/include/llvm/DebugInfo/PDB/DIA/DIAEnumDebugStreams.h
+file path=usr/include/llvm/DebugInfo/PDB/DIA/DIAEnumLineNumbers.h
+file path=usr/include/llvm/DebugInfo/PDB/DIA/DIAEnumSourceFiles.h
+file path=usr/include/llvm/DebugInfo/PDB/DIA/DIAEnumSymbols.h
+file path=usr/include/llvm/DebugInfo/PDB/DIA/DIALineNumber.h
+file path=usr/include/llvm/DebugInfo/PDB/DIA/DIARawSymbol.h
+file path=usr/include/llvm/DebugInfo/PDB/DIA/DIASession.h
+file path=usr/include/llvm/DebugInfo/PDB/DIA/DIASourceFile.h
+file path=usr/include/llvm/DebugInfo/PDB/DIA/DIASupport.h
+file path=usr/include/llvm/DebugInfo/PDB/IPDBDataStream.h
+file path=usr/include/llvm/DebugInfo/PDB/IPDBEnumChildren.h
+file path=usr/include/llvm/DebugInfo/PDB/IPDBLineNumber.h
+file path=usr/include/llvm/DebugInfo/PDB/IPDBRawSymbol.h
+file path=usr/include/llvm/DebugInfo/PDB/IPDBSession.h
+file path=usr/include/llvm/DebugInfo/PDB/IPDBSourceFile.h
+file path=usr/include/llvm/DebugInfo/PDB/PDB.h
+file path=usr/include/llvm/DebugInfo/PDB/PDBContext.h
+file path=usr/include/llvm/DebugInfo/PDB/PDBExtras.h
+file path=usr/include/llvm/DebugInfo/PDB/PDBSymDumper.h
+file path=usr/include/llvm/DebugInfo/PDB/PDBSymbol.h
+file path=usr/include/llvm/DebugInfo/PDB/PDBSymbolAnnotation.h
+file path=usr/include/llvm/DebugInfo/PDB/PDBSymbolBlock.h
+file path=usr/include/llvm/DebugInfo/PDB/PDBSymbolCompiland.h
+file path=usr/include/llvm/DebugInfo/PDB/PDBSymbolCompilandDetails.h
+file path=usr/include/llvm/DebugInfo/PDB/PDBSymbolCompilandEnv.h
+file path=usr/include/llvm/DebugInfo/PDB/PDBSymbolCustom.h
+file path=usr/include/llvm/DebugInfo/PDB/PDBSymbolData.h
+file path=usr/include/llvm/DebugInfo/PDB/PDBSymbolExe.h
+file path=usr/include/llvm/DebugInfo/PDB/PDBSymbolFunc.h
+file path=usr/include/llvm/DebugInfo/PDB/PDBSymbolFuncDebugEnd.h
+file path=usr/include/llvm/DebugInfo/PDB/PDBSymbolFuncDebugStart.h
+file path=usr/include/llvm/DebugInfo/PDB/PDBSymbolLabel.h
+file path=usr/include/llvm/DebugInfo/PDB/PDBSymbolPublicSymbol.h
+file path=usr/include/llvm/DebugInfo/PDB/PDBSymbolThunk.h
+file path=usr/include/llvm/DebugInfo/PDB/PDBSymbolTypeArray.h
+file path=usr/include/llvm/DebugInfo/PDB/PDBSymbolTypeBaseClass.h
+file path=usr/include/llvm/DebugInfo/PDB/PDBSymbolTypeBuiltin.h
+file path=usr/include/llvm/DebugInfo/PDB/PDBSymbolTypeCustom.h
+file path=usr/include/llvm/DebugInfo/PDB/PDBSymbolTypeDimension.h
+file path=usr/include/llvm/DebugInfo/PDB/PDBSymbolTypeEnum.h
+file path=usr/include/llvm/DebugInfo/PDB/PDBSymbolTypeFriend.h
+file path=usr/include/llvm/DebugInfo/PDB/PDBSymbolTypeFunctionArg.h
+file path=usr/include/llvm/DebugInfo/PDB/PDBSymbolTypeFunctionSig.h
+file path=usr/include/llvm/DebugInfo/PDB/PDBSymbolTypeManaged.h
+file path=usr/include/llvm/DebugInfo/PDB/PDBSymbolTypePointer.h
+file path=usr/include/llvm/DebugInfo/PDB/PDBSymbolTypeTypedef.h
+file path=usr/include/llvm/DebugInfo/PDB/PDBSymbolTypeUDT.h
+file path=usr/include/llvm/DebugInfo/PDB/PDBSymbolTypeVTable.h
+file path=usr/include/llvm/DebugInfo/PDB/PDBSymbolTypeVTableShape.h
+file path=usr/include/llvm/DebugInfo/PDB/PDBSymbolUnknown.h
+file path=usr/include/llvm/DebugInfo/PDB/PDBSymbolUsingNamespace.h
+file path=usr/include/llvm/DebugInfo/PDB/PDBTypes.h
+file path=usr/include/llvm/DebugInfo/Symbolize/DIPrinter.h
+file path=usr/include/llvm/DebugInfo/Symbolize/SymbolizableModule.h
+file path=usr/include/llvm/DebugInfo/Symbolize/Symbolize.h
 file path=usr/include/llvm/ExecutionEngine/ExecutionEngine.h
 file path=usr/include/llvm/ExecutionEngine/GenericValue.h
 file path=usr/include/llvm/ExecutionEngine/Interpreter.h
 file path=usr/include/llvm/ExecutionEngine/JITEventListener.h
+file path=usr/include/llvm/ExecutionEngine/JITSymbolFlags.h
 file path=usr/include/llvm/ExecutionEngine/MCJIT.h
 file path=usr/include/llvm/ExecutionEngine/OProfileWrapper.h
 file path=usr/include/llvm/ExecutionEngine/ObjectCache.h
+file path=usr/include/llvm/ExecutionEngine/ObjectMemoryBuffer.h
+file path=usr/include/llvm/ExecutionEngine/Orc/CompileOnDemandLayer.h
+file path=usr/include/llvm/ExecutionEngine/Orc/CompileUtils.h
+file path=usr/include/llvm/ExecutionEngine/Orc/ExecutionUtils.h
+file path=usr/include/llvm/ExecutionEngine/Orc/GlobalMappingLayer.h
+file path=usr/include/llvm/ExecutionEngine/Orc/IRCompileLayer.h
+file path=usr/include/llvm/ExecutionEngine/Orc/IRTransformLayer.h
+file path=usr/include/llvm/ExecutionEngine/Orc/IndirectionUtils.h
+file path=usr/include/llvm/ExecutionEngine/Orc/JITSymbol.h
+file path=usr/include/llvm/ExecutionEngine/Orc/LambdaResolver.h
+file path=usr/include/llvm/ExecutionEngine/Orc/LazyEmittingLayer.h
+file path=usr/include/llvm/ExecutionEngine/Orc/LogicalDylib.h
+file path=usr/include/llvm/ExecutionEngine/Orc/NullResolver.h
+file path=usr/include/llvm/ExecutionEngine/Orc/ObjectLinkingLayer.h
+file path=usr/include/llvm/ExecutionEngine/Orc/ObjectTransformLayer.h
+file path=usr/include/llvm/ExecutionEngine/Orc/OrcArchitectureSupport.h
+file path=usr/include/llvm/ExecutionEngine/Orc/OrcError.h
+file path=usr/include/llvm/ExecutionEngine/Orc/OrcRemoteTargetClient.h
+file path=usr/include/llvm/ExecutionEngine/Orc/OrcRemoteTargetRPCAPI.h
+file path=usr/include/llvm/ExecutionEngine/Orc/OrcRemoteTargetServer.h
+file path=usr/include/llvm/ExecutionEngine/Orc/RPCChannel.h
+file path=usr/include/llvm/ExecutionEngine/Orc/RPCUtils.h
+file path=usr/include/llvm/ExecutionEngine/OrcMCJITReplacement.h
 file path=usr/include/llvm/ExecutionEngine/RTDyldMemoryManager.h
 file path=usr/include/llvm/ExecutionEngine/RuntimeDyld.h
 file path=usr/include/llvm/ExecutionEngine/RuntimeDyldChecker.h
@@ -313,6 +437,8 @@
 file path=usr/include/llvm/IR/Argument.h
 file path=usr/include/llvm/IR/AssemblyAnnotationWriter.h
 file path=usr/include/llvm/IR/Attributes.h
+file path=usr/include/llvm/IR/Attributes.inc
+file path=usr/include/llvm/IR/Attributes.td
 file path=usr/include/llvm/IR/AutoUpgrade.h
 file path=usr/include/llvm/IR/BasicBlock.h
 file path=usr/include/llvm/IR/CFG.h
@@ -326,12 +452,15 @@
 file path=usr/include/llvm/IR/DIBuilder.h
 file path=usr/include/llvm/IR/DataLayout.h
 file path=usr/include/llvm/IR/DebugInfo.h
+file path=usr/include/llvm/IR/DebugInfoFlags.def
+file path=usr/include/llvm/IR/DebugInfoMetadata.h
 file path=usr/include/llvm/IR/DebugLoc.h
 file path=usr/include/llvm/IR/DerivedTypes.h
 file path=usr/include/llvm/IR/DiagnosticInfo.h
 file path=usr/include/llvm/IR/DiagnosticPrinter.h
 file path=usr/include/llvm/IR/Dominators.h
 file path=usr/include/llvm/IR/Function.h
+file path=usr/include/llvm/IR/FunctionInfo.h
 file path=usr/include/llvm/IR/GVMaterializer.h
 file path=usr/include/llvm/IR/GetElementPtrTypeIterator.h
 file path=usr/include/llvm/IR/GlobalAlias.h
@@ -352,12 +481,15 @@
 file path=usr/include/llvm/IR/Intrinsics.h
 file path=usr/include/llvm/IR/Intrinsics.td
 file path=usr/include/llvm/IR/IntrinsicsAArch64.td
+file path=usr/include/llvm/IR/IntrinsicsAMDGPU.td
 file path=usr/include/llvm/IR/IntrinsicsARM.td
+file path=usr/include/llvm/IR/IntrinsicsBPF.td
 file path=usr/include/llvm/IR/IntrinsicsHexagon.td
 file path=usr/include/llvm/IR/IntrinsicsMips.td
 file path=usr/include/llvm/IR/IntrinsicsNVVM.td
 file path=usr/include/llvm/IR/IntrinsicsPowerPC.td
-file path=usr/include/llvm/IR/IntrinsicsR600.td
+file path=usr/include/llvm/IR/IntrinsicsSystemZ.td
+file path=usr/include/llvm/IR/IntrinsicsWebAssembly.td
 file path=usr/include/llvm/IR/IntrinsicsX86.td
 file path=usr/include/llvm/IR/IntrinsicsXCore.td
 file path=usr/include/llvm/IR/LLVMContext.h
@@ -368,8 +500,8 @@
 file path=usr/include/llvm/IR/Mangler.h
 file path=usr/include/llvm/IR/Metadata.def
 file path=usr/include/llvm/IR/Metadata.h
-file path=usr/include/llvm/IR/MetadataTracking.h
 file path=usr/include/llvm/IR/Module.h
+file path=usr/include/llvm/IR/ModuleSlotTracker.h
 file path=usr/include/llvm/IR/NoFolder.h
 file path=usr/include/llvm/IR/OperandTraits.h
 file path=usr/include/llvm/IR/Operator.h
@@ -386,6 +518,7 @@
 file path=usr/include/llvm/IR/Use.h
 file path=usr/include/llvm/IR/UseListOrder.h
 file path=usr/include/llvm/IR/User.h
+file path=usr/include/llvm/IR/Value.def
 file path=usr/include/llvm/IR/Value.h
 file path=usr/include/llvm/IR/ValueHandle.h
 file path=usr/include/llvm/IR/ValueMap.h
@@ -395,9 +528,11 @@
 file path=usr/include/llvm/InitializePasses.h
 file path=usr/include/llvm/LTO/LTOCodeGenerator.h
 file path=usr/include/llvm/LTO/LTOModule.h
+file path=usr/include/llvm/LibDriver/LibDriver.h
 file path=usr/include/llvm/LineEditor/LineEditor.h
 file path=usr/include/llvm/LinkAllIR.h
 file path=usr/include/llvm/LinkAllPasses.h
+file path=usr/include/llvm/Linker/IRMover.h
 file path=usr/include/llvm/Linker/Linker.h
 file path=usr/include/llvm/MC/ConstantPools.h
 file path=usr/include/llvm/MC/MCAsmBackend.h
@@ -413,15 +548,14 @@
 file path=usr/include/llvm/MC/MCDirectives.h
 file path=usr/include/llvm/MC/MCDisassembler.h
 file path=usr/include/llvm/MC/MCDwarf.h
-file path=usr/include/llvm/MC/MCELF.h
 file path=usr/include/llvm/MC/MCELFObjectWriter.h
 file path=usr/include/llvm/MC/MCELFStreamer.h
-file path=usr/include/llvm/MC/MCELFSymbolFlags.h
 file path=usr/include/llvm/MC/MCExpr.h
 file path=usr/include/llvm/MC/MCExternalSymbolizer.h
 file path=usr/include/llvm/MC/MCFixedLenDisassembler.h
 file path=usr/include/llvm/MC/MCFixup.h
 file path=usr/include/llvm/MC/MCFixupKindInfo.h
+file path=usr/include/llvm/MC/MCFragment.h
 file path=usr/include/llvm/MC/MCInst.h
 file path=usr/include/llvm/MC/MCInstBuilder.h
 file path=usr/include/llvm/MC/MCInstPrinter.h
@@ -431,7 +565,6 @@
 file path=usr/include/llvm/MC/MCInstrItineraries.h
 file path=usr/include/llvm/MC/MCLabel.h
 file path=usr/include/llvm/MC/MCLinkerOptimizationHint.h
-file path=usr/include/llvm/MC/MCMachOSymbolFlags.h
 file path=usr/include/llvm/MC/MCMachObjectWriter.h
 file path=usr/include/llvm/MC/MCObjectFileInfo.h
 file path=usr/include/llvm/MC/MCObjectStreamer.h
@@ -441,6 +574,7 @@
 file path=usr/include/llvm/MC/MCParser/MCAsmLexer.h
 file path=usr/include/llvm/MC/MCParser/MCAsmParser.h
 file path=usr/include/llvm/MC/MCParser/MCAsmParserExtension.h
+file path=usr/include/llvm/MC/MCParser/MCAsmParserUtils.h
 file path=usr/include/llvm/MC/MCParser/MCParsedAsmOperand.h
 file path=usr/include/llvm/MC/MCRegisterInfo.h
 file path=usr/include/llvm/MC/MCRelocationInfo.h
@@ -452,6 +586,9 @@
 file path=usr/include/llvm/MC/MCStreamer.h
 file path=usr/include/llvm/MC/MCSubtargetInfo.h
 file path=usr/include/llvm/MC/MCSymbol.h
+file path=usr/include/llvm/MC/MCSymbolCOFF.h
+file path=usr/include/llvm/MC/MCSymbolELF.h
+file path=usr/include/llvm/MC/MCSymbolMachO.h
 file path=usr/include/llvm/MC/MCSymbolizer.h
 file path=usr/include/llvm/MC/MCTargetAsmParser.h
 file path=usr/include/llvm/MC/MCTargetOptions.h
@@ -467,19 +604,24 @@
 file path=usr/include/llvm/MC/SubtargetFeature.h
 file path=usr/include/llvm/MC/YAML.h
 file path=usr/include/llvm/Object/Archive.h
+file path=usr/include/llvm/Object/ArchiveWriter.h
 file path=usr/include/llvm/Object/Binary.h
 file path=usr/include/llvm/Object/COFF.h
+file path=usr/include/llvm/Object/COFFImportFile.h
 file path=usr/include/llvm/Object/COFFYAML.h
 file path=usr/include/llvm/Object/ELF.h
 file path=usr/include/llvm/Object/ELFObjectFile.h
 file path=usr/include/llvm/Object/ELFTypes.h
 file path=usr/include/llvm/Object/ELFYAML.h
 file path=usr/include/llvm/Object/Error.h
+file path=usr/include/llvm/Object/FunctionIndexObjectFile.h
 file path=usr/include/llvm/Object/IRObjectFile.h
 file path=usr/include/llvm/Object/MachO.h
 file path=usr/include/llvm/Object/MachOUniversal.h
 file path=usr/include/llvm/Object/ObjectFile.h
 file path=usr/include/llvm/Object/RelocVisitor.h
+file path=usr/include/llvm/Object/StackMapParser.h
+file path=usr/include/llvm/Object/SymbolSize.h
 file path=usr/include/llvm/Object/SymbolicFile.h
 file path=usr/include/llvm/Option/Arg.h
 file path=usr/include/llvm/Option/ArgList.h
@@ -490,13 +632,14 @@
 file path=usr/include/llvm/Pass.h
 file path=usr/include/llvm/PassAnalysisSupport.h
 file path=usr/include/llvm/PassInfo.h
-file path=usr/include/llvm/PassManager.h
 file path=usr/include/llvm/PassRegistry.h
 file path=usr/include/llvm/PassSupport.h
+file path=usr/include/llvm/Passes/PassBuilder.h
 file path=usr/include/llvm/ProfileData/CoverageMapping.h
 file path=usr/include/llvm/ProfileData/CoverageMappingReader.h
 file path=usr/include/llvm/ProfileData/CoverageMappingWriter.h
 file path=usr/include/llvm/ProfileData/InstrProf.h
+file path=usr/include/llvm/ProfileData/InstrProfData.inc
 file path=usr/include/llvm/ProfileData/InstrProfReader.h
 file path=usr/include/llvm/ProfileData/InstrProfWriter.h
 file path=usr/include/llvm/ProfileData/SampleProf.h
@@ -505,6 +648,7 @@
 file path=usr/include/llvm/Support/AIXDataTypesFix.h
 file path=usr/include/llvm/Support/ARMBuildAttributes.h
 file path=usr/include/llvm/Support/ARMEHABI.h
+file path=usr/include/llvm/Support/ARMTargetParser.def
 file path=usr/include/llvm/Support/ARMWinEH.h
 file path=usr/include/llvm/Support/AlignOf.h
 file path=usr/include/llvm/Support/Allocator.h
@@ -514,6 +658,7 @@
 file path=usr/include/llvm/Support/BranchProbability.h
 file path=usr/include/llvm/Support/CBindingWrapping.h
 file path=usr/include/llvm/Support/COFF.h
+file path=usr/include/llvm/Support/COM.h
 file path=usr/include/llvm/Support/Capacity.h
 file path=usr/include/llvm/Support/Casting.h
 file path=usr/include/llvm/Support/CodeGen.h
@@ -527,17 +672,20 @@
 file path=usr/include/llvm/Support/DataStream.h
 file path=usr/include/llvm/Support/DataTypes.h
 file path=usr/include/llvm/Support/Debug.h
+file path=usr/include/llvm/Support/Dwarf.def
 file path=usr/include/llvm/Support/Dwarf.h
 file path=usr/include/llvm/Support/DynamicLibrary.h
 file path=usr/include/llvm/Support/ELF.h
 file path=usr/include/llvm/Support/ELFRelocs/AArch64.def
 file path=usr/include/llvm/Support/ELFRelocs/ARM.def
+file path=usr/include/llvm/Support/ELFRelocs/AVR.def
 file path=usr/include/llvm/Support/ELFRelocs/Hexagon.def
 file path=usr/include/llvm/Support/ELFRelocs/Mips.def
 file path=usr/include/llvm/Support/ELFRelocs/PowerPC.def
 file path=usr/include/llvm/Support/ELFRelocs/PowerPC64.def
 file path=usr/include/llvm/Support/ELFRelocs/Sparc.def
 file path=usr/include/llvm/Support/ELFRelocs/SystemZ.def
+file path=usr/include/llvm/Support/ELFRelocs/WebAssembly.def
 file path=usr/include/llvm/Support/ELFRelocs/i386.def
 file path=usr/include/llvm/Support/ELFRelocs/x86_64.def
 file path=usr/include/llvm/Support/Endian.h
@@ -556,6 +704,7 @@
 file path=usr/include/llvm/Support/GenericDomTreeConstruction.h
 file path=usr/include/llvm/Support/GraphWriter.h
 file path=usr/include/llvm/Support/Host.h
+file path=usr/include/llvm/Support/JamCRC.h
 file path=usr/include/llvm/Support/LEB128.h
 file path=usr/include/llvm/Support/LICENSE.TXT
 file path=usr/include/llvm/Support/LineIterator.h
@@ -568,15 +717,16 @@
 file path=usr/include/llvm/Support/Memory.h
 file path=usr/include/llvm/Support/MemoryBuffer.h
 file path=usr/include/llvm/Support/MemoryObject.h
+file path=usr/include/llvm/Support/MipsABIFlags.h
 file path=usr/include/llvm/Support/Mutex.h
 file path=usr/include/llvm/Support/MutexGuard.h
 file path=usr/include/llvm/Support/OnDiskHashTable.h
 file path=usr/include/llvm/Support/Options.h
-file path=usr/include/llvm/Support/OutputBuffer.h
 file path=usr/include/llvm/Support/Path.h
 file path=usr/include/llvm/Support/PluginLoader.h
 file path=usr/include/llvm/Support/PointerLikeTypeTraits.h
 file path=usr/include/llvm/Support/PrettyStackTrace.h
+file path=usr/include/llvm/Support/Printable.h
 file path=usr/include/llvm/Support/Process.h
 file path=usr/include/llvm/Support/Program.h
 file path=usr/include/llvm/Support/RWMutex.h
@@ -595,15 +745,19 @@
 file path=usr/include/llvm/Support/SpecialCaseList.h
 file path=usr/include/llvm/Support/StreamingMemoryObject.h
 file path=usr/include/llvm/Support/StringPool.h
+file path=usr/include/llvm/Support/StringSaver.h
 file path=usr/include/llvm/Support/SwapByteOrder.h
 file path=usr/include/llvm/Support/SystemUtils.h
+file path=usr/include/llvm/Support/TargetParser.h
 file path=usr/include/llvm/Support/TargetRegistry.h
 file path=usr/include/llvm/Support/TargetSelect.h
 file path=usr/include/llvm/Support/ThreadLocal.h
+file path=usr/include/llvm/Support/ThreadPool.h
 file path=usr/include/llvm/Support/Threading.h
 file path=usr/include/llvm/Support/TimeValue.h
 file path=usr/include/llvm/Support/Timer.h
 file path=usr/include/llvm/Support/ToolOutputFile.h
+file path=usr/include/llvm/Support/TrailingObjects.h
 file path=usr/include/llvm/Support/Unicode.h
 file path=usr/include/llvm/Support/UnicodeCharRanges.h
 file path=usr/include/llvm/Support/UniqueLock.h
@@ -616,6 +770,7 @@
 file path=usr/include/llvm/Support/circular_raw_ostream.h
 file path=usr/include/llvm/Support/raw_os_ostream.h
 file path=usr/include/llvm/Support/raw_ostream.h
+file path=usr/include/llvm/Support/thread.h
 file path=usr/include/llvm/Support/type_traits.h
 file path=usr/include/llvm/TableGen/Error.h
 file path=usr/include/llvm/TableGen/Main.h
@@ -632,23 +787,35 @@
 file path=usr/include/llvm/Target/TargetInstrInfo.h
 file path=usr/include/llvm/Target/TargetIntrinsicInfo.h
 file path=usr/include/llvm/Target/TargetItinerary.td
-file path=usr/include/llvm/Target/TargetLibraryInfo.h
 file path=usr/include/llvm/Target/TargetLowering.h
 file path=usr/include/llvm/Target/TargetLoweringObjectFile.h
 file path=usr/include/llvm/Target/TargetMachine.h
 file path=usr/include/llvm/Target/TargetOpcodes.h
 file path=usr/include/llvm/Target/TargetOptions.h
+file path=usr/include/llvm/Target/TargetRecip.h
 file path=usr/include/llvm/Target/TargetRegisterInfo.h
 file path=usr/include/llvm/Target/TargetSchedule.td
 file path=usr/include/llvm/Target/TargetSelectionDAG.td
 file path=usr/include/llvm/Target/TargetSelectionDAGInfo.h
 file path=usr/include/llvm/Target/TargetSubtargetInfo.h
 file path=usr/include/llvm/Transforms/IPO.h
+file path=usr/include/llvm/Transforms/IPO/ForceFunctionAttrs.h
+file path=usr/include/llvm/Transforms/IPO/FunctionImport.h
+file path=usr/include/llvm/Transforms/IPO/InferFunctionAttrs.h
 file path=usr/include/llvm/Transforms/IPO/InlinerPass.h
+file path=usr/include/llvm/Transforms/IPO/LowerBitSets.h
 file path=usr/include/llvm/Transforms/IPO/PassManagerBuilder.h
+file path=usr/include/llvm/Transforms/IPO/StripDeadPrototypes.h
+file path=usr/include/llvm/Transforms/InstCombine/InstCombine.h
+file path=usr/include/llvm/Transforms/InstCombine/InstCombineWorklist.h
 file path=usr/include/llvm/Transforms/Instrumentation.h
 file path=usr/include/llvm/Transforms/ObjCARC.h
 file path=usr/include/llvm/Transforms/Scalar.h
+file path=usr/include/llvm/Transforms/Scalar/ADCE.h
+file path=usr/include/llvm/Transforms/Scalar/EarlyCSE.h
+file path=usr/include/llvm/Transforms/Scalar/LowerExpectIntrinsic.h
+file path=usr/include/llvm/Transforms/Scalar/SROA.h
+file path=usr/include/llvm/Transforms/Scalar/SimplifyCFG.h
 file path=usr/include/llvm/Transforms/Utils/ASanStackFrameLayout.h
 file path=usr/include/llvm/Transforms/Utils/BasicBlockUtils.h
 file path=usr/include/llvm/Transforms/Utils/BuildLibCalls.h
@@ -661,17 +828,18 @@
 file path=usr/include/llvm/Transforms/Utils/IntegerDivision.h
 file path=usr/include/llvm/Transforms/Utils/Local.h
 file path=usr/include/llvm/Transforms/Utils/LoopUtils.h
+file path=usr/include/llvm/Transforms/Utils/LoopVersioning.h
 file path=usr/include/llvm/Transforms/Utils/ModuleUtils.h
 file path=usr/include/llvm/Transforms/Utils/PromoteMemToReg.h
 file path=usr/include/llvm/Transforms/Utils/SSAUpdater.h
 file path=usr/include/llvm/Transforms/Utils/SSAUpdaterImpl.h
 file path=usr/include/llvm/Transforms/Utils/SimplifyIndVar.h
 file path=usr/include/llvm/Transforms/Utils/SimplifyLibCalls.h
+file path=usr/include/llvm/Transforms/Utils/SplitModule.h
 file path=usr/include/llvm/Transforms/Utils/SymbolRewriter.h
 file path=usr/include/llvm/Transforms/Utils/UnifyFunctionExitNodes.h
 file path=usr/include/llvm/Transforms/Utils/UnrollLoop.h
 file path=usr/include/llvm/Transforms/Utils/ValueMapper.h
-file path=usr/include/llvm/Transforms/Utils/VectorUtils.h
 file path=usr/include/llvm/Transforms/Vectorize.h
 file path=usr/lib/$(MACH64)/libLLVMAnalysis.a
 file path=usr/lib/$(MACH64)/libLLVMAsmParser.a
@@ -680,22 +848,28 @@
 file path=usr/lib/$(MACH64)/libLLVMBitWriter.a
 file path=usr/lib/$(MACH64)/libLLVMCodeGen.a
 file path=usr/lib/$(MACH64)/libLLVMCore.a
-file path=usr/lib/$(MACH64)/libLLVMDebugInfo.a
+file path=usr/lib/$(MACH64)/libLLVMDebugInfoCodeView.a
+file path=usr/lib/$(MACH64)/libLLVMDebugInfoDWARF.a
+file path=usr/lib/$(MACH64)/libLLVMDebugInfoPDB.a
 file path=usr/lib/$(MACH64)/libLLVMExecutionEngine.a
 file path=usr/lib/$(MACH64)/libLLVMIRReader.a
 file path=usr/lib/$(MACH64)/libLLVMInstCombine.a
 file path=usr/lib/$(MACH64)/libLLVMInstrumentation.a
 file path=usr/lib/$(MACH64)/libLLVMInterpreter.a
 file path=usr/lib/$(MACH64)/libLLVMLTO.a
+file path=usr/lib/$(MACH64)/libLLVMLibDriver.a
 file path=usr/lib/$(MACH64)/libLLVMLineEditor.a
 file path=usr/lib/$(MACH64)/libLLVMLinker.a
 file path=usr/lib/$(MACH64)/libLLVMMC.a
 file path=usr/lib/$(MACH64)/libLLVMMCDisassembler.a
 file path=usr/lib/$(MACH64)/libLLVMMCJIT.a
 file path=usr/lib/$(MACH64)/libLLVMMCParser.a
+file path=usr/lib/$(MACH64)/libLLVMMIRParser.a
 file path=usr/lib/$(MACH64)/libLLVMObjCARCOpts.a
 file path=usr/lib/$(MACH64)/libLLVMObject.a
 file path=usr/lib/$(MACH64)/libLLVMOption.a
+file path=usr/lib/$(MACH64)/libLLVMOrcJIT.a
+file path=usr/lib/$(MACH64)/libLLVMPasses.a
 file path=usr/lib/$(MACH64)/libLLVMProfileData.a
 file path=usr/lib/$(MACH64)/libLLVMRuntimeDyld.a
 file path=usr/lib/$(MACH64)/libLLVMScalarOpts.a
@@ -707,6 +881,7 @@
 file path=usr/lib/$(MACH64)/libLLVMSparcDisassembler.a variant.arch=sparc
 file path=usr/lib/$(MACH64)/libLLVMSparcInfo.a variant.arch=sparc
 file path=usr/lib/$(MACH64)/libLLVMSupport.a
+file path=usr/lib/$(MACH64)/libLLVMSymbolize.a
 file path=usr/lib/$(MACH64)/libLLVMTableGen.a
 file path=usr/lib/$(MACH64)/libLLVMTarget.a
 file path=usr/lib/$(MACH64)/libLLVMTransformUtils.a
@@ -718,15 +893,15 @@
 file path=usr/lib/$(MACH64)/libLLVMX86Disassembler.a variant.arch=i386
 file path=usr/lib/$(MACH64)/libLLVMX86Info.a variant.arch=i386
 file path=usr/lib/$(MACH64)/libLLVMX86Utils.a variant.arch=i386
-file path=usr/lib/$(MACH64)/libLLVMipa.a
 file path=usr/lib/$(MACH64)/libLLVMipo.a
-file path=usr/lib/$(MACH64)/libLTO.a
+#
 file path=usr/share/llvm/cmake/AddLLVM.cmake
 file path=usr/share/llvm/cmake/AddLLVMDefinitions.cmake
 file path=usr/share/llvm/cmake/AddOCaml.cmake
 file path=usr/share/llvm/cmake/AddSphinxTarget.cmake
 file path=usr/share/llvm/cmake/ChooseMSVCCRT.cmake
 file path=usr/share/llvm/cmake/CrossCompile.cmake
+file path=usr/share/llvm/cmake/DetermineGCCCompatible.cmake
 file path=usr/share/llvm/cmake/FindOCaml.cmake
 file path=usr/share/llvm/cmake/FindSphinx.cmake
 file path=usr/share/llvm/cmake/GetSVN.cmake
@@ -736,7 +911,8 @@
 file path=usr/share/llvm/cmake/LLVMConfig.cmake
 file path=usr/share/llvm/cmake/LLVMConfigVersion.cmake
 file path=usr/share/llvm/cmake/LLVMExports.cmake
-file path=usr/share/llvm/cmake/LLVMParseArguments.cmake
+file path=usr/share/llvm/cmake/LLVMExternalProjectUtils.cmake
+file path=usr/share/llvm/cmake/LLVMInstallSymlink.cmake
 file path=usr/share/llvm/cmake/LLVMProcessSources.cmake
 file path=usr/share/llvm/cmake/TableGen.cmake
 license llvm.license license="University of Illinois/NCSA"
--- a/components/llvm/llvm.p5m	Thu Jul 28 16:15:45 2016 -0700
+++ b/components/llvm/llvm.p5m	Thu Jul 28 16:25:34 2016 -0700
@@ -23,6 +23,7 @@
 # Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
 #
 
+<transform file path=usr.*/man/.+ -> default mangler.man.stability uncommitted>
 set name=pkg.fmri \
     value=pkg:/developer/llvm/llvm@$(IPS_COMPONENT_VERSION),$(BUILD_VERSION)
 set name=pkg.summary \
@@ -38,49 +39,73 @@
 set name=info.upstream-url value=$(COMPONENT_PROJECT_URL)
 set name=org.opensolaris.arc-caseid value=PSARC/2013/188
 set name=org.opensolaris.consolidation value=$(CONSOLIDATION)
-file path=usr/bin/FileCheck
-file path=usr/bin/bugpoint
-file path=usr/bin/count
-file path=usr/bin/llc
-file path=usr/bin/lli
-file path=usr/bin/lli-child-target
-file path=usr/bin/llvm-ar
-file path=usr/bin/llvm-as
-file path=usr/bin/llvm-bcanalyzer
-file path=usr/bin/llvm-config
-file path=usr/bin/llvm-cov
-file path=usr/bin/llvm-diff
-file path=usr/bin/llvm-dis
-file path=usr/bin/llvm-dsymutil
-file path=usr/bin/llvm-dwarfdump
-file path=usr/bin/llvm-extract
-file path=usr/bin/llvm-link
-file path=usr/bin/llvm-lto
-file path=usr/bin/llvm-mc
-file path=usr/bin/llvm-mcmarkup
-file path=usr/bin/llvm-nm
-file path=usr/bin/llvm-objdump
-file path=usr/bin/llvm-profdata
+file usr/bin/$(MACH64)/bugpoint path=usr/bin/bugpoint
+file usr/bin/$(MACH64)/llc path=usr/bin/llc
+file usr/bin/$(MACH64)/lli path=usr/bin/lli
+file usr/bin/$(MACH64)/llvm-ar path=usr/bin/llvm-ar
+file usr/bin/$(MACH64)/llvm-as path=usr/bin/llvm-as
+file usr/bin/$(MACH64)/llvm-bcanalyzer path=usr/bin/llvm-bcanalyzer
+file usr/bin/$(MACH64)/llvm-c-test path=usr/bin/llvm-c-test
+file usr/bin/$(MACH64)/llvm-config path=usr/bin/llvm-config
+file usr/bin/$(MACH64)/llvm-cov path=usr/bin/llvm-cov
+file usr/bin/$(MACH64)/llvm-cxxdump path=usr/bin/llvm-cxxdump
+file usr/bin/$(MACH64)/llvm-diff path=usr/bin/llvm-diff
+file usr/bin/$(MACH64)/llvm-dis path=usr/bin/llvm-dis
+file usr/bin/$(MACH64)/llvm-dsymutil path=usr/bin/llvm-dsymutil
+file usr/bin/$(MACH64)/llvm-dwarfdump path=usr/bin/llvm-dwarfdump
+file usr/bin/$(MACH64)/llvm-dwp path=usr/bin/llvm-dwp
+file usr/bin/$(MACH64)/llvm-extract path=usr/bin/llvm-extract
+hardlink path=usr/bin/llvm-lib target=llvm-ar
+file usr/bin/$(MACH64)/llvm-link path=usr/bin/llvm-link
+file usr/bin/$(MACH64)/llvm-lto path=usr/bin/llvm-lto
+file usr/bin/$(MACH64)/llvm-mc path=usr/bin/llvm-mc
+file usr/bin/$(MACH64)/llvm-mcmarkup path=usr/bin/llvm-mcmarkup
+file usr/bin/$(MACH64)/llvm-nm path=usr/bin/llvm-nm
+file usr/bin/$(MACH64)/llvm-objdump path=usr/bin/llvm-objdump
+file usr/bin/$(MACH64)/llvm-pdbdump path=usr/bin/llvm-pdbdump
+file usr/bin/$(MACH64)/llvm-profdata path=usr/bin/llvm-profdata
 hardlink path=usr/bin/llvm-ranlib target=llvm-ar
-file path=usr/bin/llvm-readobj
-file path=usr/bin/llvm-rtdyld
-file path=usr/bin/llvm-size
-file path=usr/bin/llvm-stress
-file path=usr/bin/llvm-symbolizer
-file path=usr/bin/llvm-tblgen
-file path=usr/bin/llvm-vtabledump
-file path=usr/bin/macho-dump
-file path=usr/bin/not
-file path=usr/bin/obj2yaml
-file path=usr/bin/opt
-file path=usr/bin/verify-uselistorder
-file path=usr/bin/yaml2obj
+file usr/bin/$(MACH64)/llvm-readobj path=usr/bin/llvm-readobj
+file usr/bin/$(MACH64)/llvm-rtdyld path=usr/bin/llvm-rtdyld
+file usr/bin/$(MACH64)/llvm-size path=usr/bin/llvm-size
+file usr/bin/$(MACH64)/llvm-split path=usr/bin/llvm-split
+file usr/bin/$(MACH64)/llvm-stress path=usr/bin/llvm-stress
+file usr/bin/$(MACH64)/llvm-symbolizer path=usr/bin/llvm-symbolizer
+file usr/bin/$(MACH64)/llvm-tblgen path=usr/bin/llvm-tblgen
+file usr/bin/$(MACH64)/obj2yaml path=usr/bin/obj2yaml
+file usr/bin/$(MACH64)/opt path=usr/bin/opt
+file usr/bin/$(MACH64)/sancov path=usr/bin/sancov
+file usr/bin/$(MACH64)/verify-uselistorder path=usr/bin/verify-uselistorder
+file usr/bin/$(MACH64)/yaml2obj path=usr/bin/yaml2obj
 file path=usr/lib/$(MACH64)/BugpointPasses.so
 file path=usr/lib/$(MACH64)/LLVMHello.so
-link path=usr/lib/$(MACH64)/libLLVM-$(COMPONENT_VERSION).so \
-    target=libLLVM-3.6.so
-file path=usr/lib/$(MACH64)/libLLVM-3.6.so
+file path=usr/lib/$(MACH64)/libLLVM-3.8.so
+link path=usr/lib/$(MACH64)/libLLVM.so target=libLLVM-3.8.so
 file path=usr/lib/$(MACH64)/libLTO.so
+file path=usr/share/man/man1/FileCheck.1
+file path=usr/share/man/man1/bugpoint.1
+file path=usr/share/man/man1/lit.1
+file path=usr/share/man/man1/llc.1
+file path=usr/share/man/man1/lli.1
+file path=usr/share/man/man1/llvm-ar.1
+file path=usr/share/man/man1/llvm-as.1
+file path=usr/share/man/man1/llvm-bcanalyzer.1
+file path=usr/share/man/man1/llvm-build.1
+file path=usr/share/man/man1/llvm-config.1
+file path=usr/share/man/man1/llvm-cov.1
+file path=usr/share/man/man1/llvm-diff.1
+file path=usr/share/man/man1/llvm-dis.1
+file path=usr/share/man/man1/llvm-dwarfdump.1
+file path=usr/share/man/man1/llvm-extract.1
+file path=usr/share/man/man1/llvm-lib.1
+file path=usr/share/man/man1/llvm-link.1
+file path=usr/share/man/man1/llvm-nm.1
+file path=usr/share/man/man1/llvm-profdata.1
+file path=usr/share/man/man1/llvm-readobj.1
+file path=usr/share/man/man1/llvm-stress.1
+file path=usr/share/man/man1/llvm-symbolizer.1
+file path=usr/share/man/man1/opt.1
+file path=usr/share/man/man1/tblgen.1
 license llvm.license license="University of Illinois/NCSA"
 depend type=require fmri=pkg:/developer/gcc-49
 depend type=require fmri=pkg:/developer/gnu-binutils
--- a/components/llvm/patches/000-AutoRegen.sh.patch	Thu Jul 28 16:15:45 2016 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,26 +0,0 @@
-# Solaris autoconf-based build.
-# https://llvm.org/bugs/show_bug.cgi?id=24641
---- autoconf/AutoRegen.sh	2014-02-28 13:17:54.000000000 -0500
-+++ autoconf/AutoRegen.sh	2015-07-18 15:03:22.104835693 -0400
-@@ -19,6 +19,21 @@
- want_aclocal_version='1\.9\.6'
- ### END NOTE #########################################################
- 
-+UNAMES="`uname -s`"
-+UNAMER="`uname -r`"
-+
-+if [ "${UNAMES}" = "SunOS" ] ; then
-+  if [ "${UNAMER}" = "5.11" ] ; then
-+    want_autoconf_version='2\.68'
-+    want_autoheader_version=$want_autoconf_version
-+    want_aclocal_version='1\.11\.2'
-+  elif [ "${UNAMER}" = "5.12" ] ; then
-+    want_autoconf_version='2\.69'
-+    want_autoheader_version=$want_autoconf_version
-+    want_aclocal_version='1\.15'
-+  fi
-+fi
-+
- outfile=configure
- configfile=configure.ac
- 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/000-solaris-LLVM-libLLVMTransforms.patch	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,23 @@
+# 24314638 LLVM CommandLine subsystem is busted
+# 3.9.X for upstream.
+--- lib/Transforms/Instrumentation/GCOVProfiling.cpp	2016-01-25 14:24:50.000000000 -0800
++++ lib/Transforms/Instrumentation/GCOVProfiling.cpp	2016-05-11 19:11:39.817769093 -0700
+@@ -45,10 +45,14 @@
+ #define DEBUG_TYPE "insert-gcov-profiling"
+ 
+ static cl::opt<std::string>
+-DefaultGCOVVersion("default-gcov-version", cl::init("402*"), cl::Hidden,
+-                   cl::ValueRequired);
+-static cl::opt<bool> DefaultExitBlockBeforeBody("gcov-exit-block-before-body",
+-                                                cl::init(false), cl::Hidden);
++DefaultGCOVVersion("default-gcov-version",
++                   cl::init(std::string("402*")),
++                   cl::Hidden, cl::ValueRequired);
++
++static cl::opt<bool>
++DefaultExitBlockBeforeBody("gcov-exit-block-before-body",
++                           cl::init(false),
++                           cl::Hidden);
+ 
+ GCOVOptions GCOVOptions::getDefault() {
+   GCOVOptions Options;
--- a/components/llvm/patches/001-Makefile.config.in.patch	Thu Jul 28 16:15:45 2016 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,43 +0,0 @@
-# Solaris autoconf-based build.
-# https://llvm.org/bugs/show_bug.cgi?id=24641
---- Makefile.config.in	2014-11-04 16:35:15.000000000 -0800
-+++ Makefile.config.in	2015-08-31 09:18:01.367776683 -0700
-@@ -12,6 +12,8 @@
- #
- #===------------------------------------------------------------------------===#
- 
-+MACH = $(shell uname -p)
-+
- # Define LLVM specific info and directories based on the autoconf variables
- LLVMPackageName   := @PACKAGE_TARNAME@
- LLVMVersion       := @PACKAGE_VERSION@
-@@ -220,6 +222,12 @@
- 
- LIBS       := @LIBS@
- 
-+ifeq ($(HOST_OS), $(filter $(HOST_OS), SunOS))
-+  ifeq ($(MACH),sparc)
-+    LIBS += -lkstat
-+  endif
-+endif
-+
- # Targets that are possible to build
- ALL_TARGETS := @ALL_TARGETS@
- 
-@@ -337,14 +345,14 @@
- ENABLE_EMBED_STDCXX := @ENABLE_EMBED_STDCXX@
- 
- # Use -fvisibility-inlines-hidden?
--ENABLE_VISIBILITY_INLINES_HIDDEN := @ENABLE_VISIBILITY_INLINES_HIDDEN@
-+ENABLE_VISIBILITY_INLINES_HIDDEN := 0
- 
- # 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
-+VERBOSE := 1
- 
- # Enable JIT for this platform
- TARGET_HAS_JIT = @TARGET_HAS_JIT@
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/001-solaris-LLVM-libLLVMCodegen.patch	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,629 @@
+# 22859423 llvm CodeGen on Intel emits a bogus .ctors section
+# 22902339 memory corruption caused by undefined behavior in LLVM IR Module
+--- include/llvm/CodeGen/CommandFlags.h	2015-12-16 14:58:30.000000000 -0500
++++ include/llvm/CodeGen/CommandFlags.h	2016-05-08 23:19:20.514430315 -0400
+@@ -38,7 +38,7 @@
+ MCPU("mcpu",
+      cl::desc("Target a specific cpu type (-mcpu=help for details)"),
+      cl::value_desc("cpu-name"),
+-     cl::init(""));
++     cl::init(std::string("")));
+ 
+ cl::list<std::string>
+ MAttrs("mattr",
+@@ -190,7 +190,7 @@
+ cl::opt<std::string>
+ TrapFuncName("trap-func", cl::Hidden,
+         cl::desc("Emit a call to trap function rather than a trap instruction"),
+-        cl::init(""));
++        cl::init(std::string("")));
+ 
+ cl::opt<bool>
+ EnablePIE("enable-pie",
+@@ -202,35 +202,42 @@
+              cl::desc("Use .ctors instead of .init_array."),
+              cl::init(false));
+ 
+-cl::opt<std::string> StopAfter("stop-after",
+-                            cl::desc("Stop compilation after a specific pass"),
+-                            cl::value_desc("pass-name"),
+-                                      cl::init(""));
+-cl::opt<std::string> StartAfter("start-after",
+-                          cl::desc("Resume compilation after a specific pass"),
+-                          cl::value_desc("pass-name"),
+-                          cl::init(""));
++cl::opt<std::string>
++StopAfter("stop-after",
++          cl::desc("Stop compilation after a specific pass"),
++          cl::value_desc("pass-name"),
++          cl::init(std::string("")));
++
++cl::opt<std::string>
++StartAfter("start-after",
++           cl::desc("Resume compilation after a specific pass"),
++           cl::value_desc("pass-name"),
++           cl::init(std::string("")));
+ 
+ cl::opt<std::string>
+-    RunPass("run-pass", cl::desc("Run compiler only for one specific pass"),
+-            cl::value_desc("pass-name"), cl::init(""));
++RunPass("run-pass", cl::desc("Run compiler only for one specific pass"),
++        cl::value_desc("pass-name"),
++        cl::init(std::string("")));
+ 
+-cl::opt<bool> DataSections("data-sections",
+-                           cl::desc("Emit data into separate sections"),
+-                           cl::init(false));
++cl::opt<bool>
++DataSections("data-sections",
++             cl::desc("Emit data into separate sections"),
++             cl::init(false));
+ 
+ cl::opt<bool>
+ FunctionSections("function-sections",
+                  cl::desc("Emit functions into separate sections"),
+                  cl::init(false));
+ 
+-cl::opt<bool> EmulatedTLS("emulated-tls",
+-                          cl::desc("Use emulated TLS model"),
+-                          cl::init(false));
+-
+-cl::opt<bool> UniqueSectionNames("unique-section-names",
+-                                 cl::desc("Give unique names to every section"),
+-                                 cl::init(true));
++cl::opt<bool>
++EmulatedTLS("emulated-tls",
++            cl::desc("Use emulated TLS model"),
++            cl::init(false));
++
++cl::opt<bool>
++UniqueSectionNames("unique-section-names",
++                   cl::desc("Give unique names to every section"),
++                   cl::init(true));
+ 
+ cl::opt<llvm::JumpTable::JumpTableType>
+ JTableType("jump-table-type",
+@@ -269,7 +276,9 @@
+ 
+ // Common utility function tightly tied to the options listed here. Initializes
+ // a TargetOptions object with CodeGen flags and returns it.
+-static inline TargetOptions InitTargetOptionsFromCodeGenFlags() {
++static inline
++__attribute__((used))
++TargetOptions InitTargetOptionsFromCodeGenFlags() {
+   TargetOptions Options;
+   Options.LessPreciseFPMADOption = EnableFPMAD;
+   Options.AllowFPOpFusion = FuseFPOps;
+###
+--- include/llvm/CodeGen/LiveInterval.h	2016-02-17 10:41:44.000000000 -0800
++++ include/llvm/CodeGen/LiveInterval.h	2016-07-08 16:53:26.422739200 -0700
+@@ -43,7 +43,7 @@
+   /// This class holds information about a machine level values, including
+   /// definition and use points.
+   ///
+-  class VNInfo {
++  class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) VNInfo {
+   public:
+     typedef BumpPtrAllocator Allocator;
+ 
+@@ -55,13 +55,11 @@
+ 
+     /// VNInfo constructor.
+     VNInfo(unsigned i, SlotIndex d)
+-      : id(i), def(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)
+-    { }
++    : id(i), def(orig.def) { }
+ 
+     /// Copy from the parameter into this VNInfo.
+     void copyFrom(VNInfo &src) {
+@@ -85,16 +83,15 @@
+   /// of live ranges, and it should be used as the primary interface for
+   /// examining live ranges around instructions.
+   class LiveQueryResult {
++  private:
+     VNInfo *const EarlyVal;
+     VNInfo *const LateVal;
+     const SlotIndex EndPoint;
+     const bool Kill;
+ 
+   public:
+-    LiveQueryResult(VNInfo *EarlyVal, VNInfo *LateVal, SlotIndex EndPoint,
+-                    bool Kill)
+-      : EarlyVal(EarlyVal), LateVal(LateVal), EndPoint(EndPoint), Kill(Kill)
+-    {}
++    LiveQueryResult(VNInfo *EV, VNInfo *LV, SlotIndex EP, bool K)
++    : EarlyVal(EV), LateVal(LV), EndPoint(EP), Kill(K) { }
+ 
+     /// 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
+@@ -157,12 +154,13 @@
+     /// This represents a simple continuous liveness interval for a value.
+     /// The start point is inclusive, the end point exclusive. These intervals
+     /// are rendered as [start,end).
+-    struct Segment {
++    class Segment {
++    public:
+       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 segment.
+ 
+-      Segment() : valno(nullptr) {}
++      Segment() : start(), end(), valno(nullptr) { }
+ 
+       Segment(SlotIndex S, SlotIndex E, VNInfo *V)
+         : start(S), end(E), valno(V) {
+@@ -190,8 +188,9 @@
+       void dump() const;
+     };
+ 
+-    typedef SmallVector<Segment,4> Segments;
+-    typedef SmallVector<VNInfo*,4> VNInfoList;
++    typedef std::vector<Segment> Segments;
++    typedef std::vector<VNInfo*> VNInfoList;
++    typedef std::set<Segment> SegmentSet;
+ 
+     Segments segments;   // the liveness segments
+     VNInfoList valnos;   // value#'s
+@@ -199,7 +198,6 @@
+     // The segment set is used temporarily to accelerate initial computation
+     // of live ranges of physical registers in computeRegUnitRange.
+     // After that the set is flushed to the segment vector and deleted.
+-    typedef std::set<Segment> SegmentSet;
+     std::unique_ptr<SegmentSet> segmentSet;
+ 
+     typedef Segments::iterator iterator;
+@@ -219,13 +217,14 @@
+     const_vni_iterator vni_end() const   { return valnos.end(); }
+ 
+     /// Constructs a new LiveRange object.
+-    LiveRange(bool UseSegmentSet = false)
+-        : segmentSet(UseSegmentSet ? llvm::make_unique<SegmentSet>()
+-                                   : nullptr) {}
++    explicit LiveRange(bool UseSegmentSet = false)
++    : segments(), valnos(),
++    segmentSet(UseSegmentSet ? llvm::make_unique<SegmentSet>() : nullptr) { }
+ 
+     /// Constructs a new LiveRange object by copying segments and valnos from
+     /// another LiveRange.
+-    LiveRange(const LiveRange &Other, BumpPtrAllocator &Allocator) {
++    LiveRange(const LiveRange &Other, BumpPtrAllocator &Allocator)
++    : segments(), valnos(), segmentSet() {
+       assert(Other.segmentSet == nullptr &&
+              "Copying of LiveRanges with active SegmentSets is not supported");
+ 
+@@ -305,8 +304,15 @@
+     /// 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);
++      size_t Size = sizeof(VNInfo) + valnos.size();
++      size_t Alignment = llvm::AlignOf<llvm::VNInfo>::Alignment;
++      void *Mem = VNInfoAllocator.Allocate(Size, Alignment);
++      assert(Mem && "VNInfoAllocator memory allocation failed!");
++
++      VNInfo *VNI = new (reinterpret_cast<VNInfo*>(Mem))
++        VNInfo(static_cast<unsigned>(valnos.size()), def);
++      assert(VNI && "VNInfo placement construction failed!");
++
+       valnos.push_back(VNI);
+       return VNI;
+     }
+@@ -320,8 +326,15 @@
+     /// for the Value number.
+     VNInfo *createValueCopy(const VNInfo *orig,
+                             VNInfo::Allocator &VNInfoAllocator) {
+-      VNInfo *VNI =
+-        new (VNInfoAllocator) VNInfo((unsigned)valnos.size(), *orig);
++      size_t Size = sizeof(VNInfo) + valnos.size();
++      size_t Alignment = llvm::AlignOf<llvm::VNInfo>::Alignment;
++      void *Mem = VNInfoAllocator.Allocate(Size, Alignment);
++      assert(Mem && "VNInfoAllocator memory allocation failed!");
++
++      VNInfo *VNI = new (reinterpret_cast<VNInfo*>(Mem))
++        VNInfo(static_cast<unsigned>(valnos.size()), *orig);
++      assert(VNI && "VNInfo placement construction failed!");
++
+       valnos.push_back(VNI);
+       return VNI;
+     }
+@@ -591,28 +604,26 @@
+ 
+   /// LiveInterval - This class represents the liveness of a register,
+   /// or stack slot.
+-  class LiveInterval : public LiveRange {
++  class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) LiveInterval : public LiveRange {
+   public:
+     typedef LiveRange super;
+ 
+     /// A live range for subregisters. The LaneMask specifies which parts of the
+     /// super register are covered by the interval.
+     /// (@sa TargetRegisterInfo::getSubRegIndexLaneMask()).
+-    class SubRange : public LiveRange {
++    class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) SubRange : public LiveRange {
+     public:
+       SubRange *Next;
+       LaneBitmask LaneMask;
+ 
+       /// Constructs a new SubRange object.
+-      SubRange(LaneBitmask LaneMask)
+-        : Next(nullptr), LaneMask(LaneMask) {
+-      }
++      explicit SubRange(LaneBitmask Mask = 0U)
++      : LiveRange(), Next(nullptr), LaneMask(Mask) { }
+ 
+       /// Constructs a new SubRange object by copying liveness from @p Other.
+-      SubRange(LaneBitmask LaneMask, const LiveRange &Other,
++      SubRange(LaneBitmask Mask, const LiveRange &Other,
+                BumpPtrAllocator &Allocator)
+-        : LiveRange(Other, Allocator), Next(nullptr), LaneMask(LaneMask) {
+-      }
++      : LiveRange(Other, Allocator), Next(nullptr), LaneMask(Mask) { }
+     };
+ 
+   private:
+@@ -623,7 +634,7 @@
+     float weight;        // weight of this interval
+ 
+     LiveInterval(unsigned Reg, float Weight)
+-      : SubRanges(nullptr), reg(Reg), weight(Weight) {}
++    : LiveRange(), SubRanges(nullptr), reg(Reg), weight(Weight) { }
+ 
+     ~LiveInterval() {
+       clearSubRanges();
+@@ -787,13 +798,14 @@
+     SlotIndex LastStart;
+     LiveRange::iterator WriteI;
+     LiveRange::iterator ReadI;
+-    SmallVector<LiveRange::Segment, 16> Spills;
++    std::vector<LiveRange::Segment> Spills;
+     void mergeSpills();
+ 
+   public:
+     /// Create a LiveRangeUpdater for adding segments to LR.
+     /// LR will temporarily be in an invalid state until flush() is called.
+-    LiveRangeUpdater(LiveRange *lr = nullptr) : LR(lr) {}
++    explicit LiveRangeUpdater(LiveRange *lr = nullptr)
++    : LR(lr), LastStart(), WriteI(), ReadI(), Spills() { }
+ 
+     ~LiveRangeUpdater() { flush(); }
+ 
+###
+--- lib/CodeGen/LiveInterval.cpp	2016-02-17 10:41:44.000000000 -0800
++++ lib/CodeGen/LiveInterval.cpp	2016-05-25 10:21:23.432898762 -0700
+@@ -320,10 +320,16 @@
+ VNInfo *LiveRange::createDeadDef(SlotIndex Def,
+                                   VNInfo::Allocator &VNInfoAllocator) {
+   // Use the segment set, if it is available.
+-  if (segmentSet != nullptr)
+-    return CalcLiveRangeUtilSet(this).createDeadDef(Def, VNInfoAllocator);
++  if (segmentSet != nullptr) {
++    CalcLiveRangeUtilSet CLR(this);
++    VNInfo *VNI = CLR.createDeadDef(Def, VNInfoAllocator);
++    return VNI;
++  }
++
+   // Otherwise use the segment vector.
+-  return CalcLiveRangeUtilVector(this).createDeadDef(Def, VNInfoAllocator);
++  CalcLiveRangeUtilVector CLR(this);
++  VNInfo *VNI = CLR.createDeadDef(Def, VNInfoAllocator);
++  return VNI;
+ }
+ 
+ // overlaps - Return true if the intersection of the two live ranges is
+@@ -740,10 +746,12 @@
+ 
+ void LiveRange::flushSegmentSet() {
+   assert(segmentSet != nullptr && "segment set must have been created");
+-  assert(
+-      segments.empty() &&
+-      "segment set can be used only initially before switching to the array");
+-  segments.append(segmentSet->begin(), segmentSet->end());
++  assert(segments.empty() &&
++         "segment set can be used only initially before "
++         "switching to the array");
++
++  segments.insert(segments.end(),
++                  segmentSet->begin(), segmentSet->end());
+   segmentSet = nullptr;
+   verify();
+ }
+###
+--- lib/CodeGen/LiveIntervalAnalysis.cpp	2016-01-07 17:16:35.000000000 -0800
++++ lib/CodeGen/LiveIntervalAnalysis.cpp	2016-05-25 08:48:39.699849409 -0700
+@@ -185,12 +185,19 @@
+ }
+ #endif
+ 
+-LiveInterval* LiveIntervals::createInterval(unsigned reg) {
+-  float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ?
++LiveInterval* LiveIntervals::createInterval(unsigned Reg) {
++  float Weight = TargetRegisterInfo::isPhysicalRegister(Reg) ?
+                   llvm::huge_valf : 0.0F;
+-  return new LiveInterval(reg, Weight);
+-}
++  void *Mem;
++  size_t Alignment = llvm::AlignOf<uint64_t>::Alignment;
++  if (posix_memalign(&Mem, Alignment, sizeof(LiveInterval)) != 0)
++    return nullptr;
++
++  (void) std::memset(Mem, 0, sizeof(LiveInterval));
+ 
++  LiveInterval *LI = new (Mem) LiveInterval(Reg, Weight);
++  return LI;
++}
+ 
+ /// computeVirtRegInterval - Compute the live interval of a virtual register,
+ /// based on defs and uses.
+###
+--- lib/CodeGen/MachineBasicBlock.cpp	2016-01-07 01:26:32.000000000 -0900
++++ lib/CodeGen/MachineBasicBlock.cpp	2016-07-07 10:45:17.893185995 -0800
+@@ -40,12 +40,16 @@
+ #define DEBUG_TYPE "codegen"
+ 
+ MachineBasicBlock::MachineBasicBlock(MachineFunction &MF, const BasicBlock *B)
+-    : BB(B), Number(-1), xParent(&MF) {
+-  Insts.Parent = this;
++  : ilist_node_with_parent<MachineBasicBlock, MachineFunction>(),
++  BB(B), Number(-1), xParent(&MF),
++  Predecessors(), Successors(), Probs(), LiveIns(),
++  Alignment(0U), IsEHPad(false), AddressTaken(false),
++  IsEHFuncletEntry(false), IsCleanupFuncletEntry(false),
++  CachedMCSymbol(nullptr) {
++    Insts.Parent = this;
+ }
+ 
+-MachineBasicBlock::~MachineBasicBlock() {
+-}
++MachineBasicBlock::~MachineBasicBlock() { }
+ 
+ /// Return the MCSymbol for this basic block.
+ MCSymbol *MachineBasicBlock::getSymbol() const {
+@@ -525,8 +529,9 @@
+                                      BranchProbability Prob) {
+   // Probability list is either empty (if successor list isn't empty, this means
+   // disabled optimization) or has the same size as successor list.
+-  if (!(Probs.empty() && !Successors.empty()))
++  if (Probs.empty() || (Probs.size() == Successors.size()))
+     Probs.push_back(Prob);
++
+   Successors.push_back(Succ);
+   Succ->addPredecessor(this);
+ }
+###.
+--- include/llvm/CodeGen/MachineBasicBlock.h	2015-12-13 00:26:17.000000000 -0900
++++ include/llvm/CodeGen/MachineBasicBlock.h	2016-07-07 10:24:28.207403130 -0800
+@@ -125,7 +125,15 @@
+   mutable MCSymbol *CachedMCSymbol = nullptr;
+ 
+   // Intrusive list support
+-  MachineBasicBlock() {}
++  MachineBasicBlock()
++  : ilist_node_with_parent<MachineBasicBlock, MachineFunction>(),
++  Insts(), BB(nullptr), Number(-1), xParent(nullptr),
++  Predecessors(), Successors(), Probs(), LiveIns(),
++  Alignment(0U), IsEHPad(false), AddressTaken(false),
++  IsEHFuncletEntry(false), IsCleanupFuncletEntry(false),
++  CachedMCSymbol(nullptr) {
++    Insts.Parent = this;
++  }
+ 
+   explicit MachineBasicBlock(MachineFunction &MF, const BasicBlock *BB);
+ 
+###
+--- lib/CodeGen/AsmPrinter/AsmPrinter.cpp	2016-01-12 17:18:13.000000000 -0800
++++ lib/CodeGen/AsmPrinter/AsmPrinter.cpp	2016-05-25 14:27:34.764865039 -0700
+@@ -1614,6 +1614,7 @@
+ };
+ } // end namespace
+ 
++
+ /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
+ /// priority.
+ void AsmPrinter::EmitXXStructorList(const DataLayout &DL, const Constant *List,
+@@ -1667,13 +1668,14 @@
+ 
+       KeySym = getSymbol(GV);
+     }
+-    MCSection *OutputSection =
+-        (isCtor ? Obj.getStaticCtorSection(S.Priority, KeySym)
+-                : Obj.getStaticDtorSection(S.Priority, KeySym));
+-    OutStreamer->SwitchSection(OutputSection);
+-    if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection())
+-      EmitAlignment(Align);
+-    EmitXXStructor(DL, S.Func);
++
++    // Why is this even necessary?
++    // Constructors for global statics are emitted in
++    // clang/lib/CodeGen/DeclCXX.cpp
++    // Destructors for global statics register themselves with __cxa_atexit.
++    // I.e. they do not need any kind of additional special handling.
++    // The only thing this does is duplicate constructor calls for
++    // global static initializations.
+   }
+ }
+ 
+###
+--- lib/CodeGen/CodeGenPrepare.cpp	2016-01-22 13:26:38.000000000 -0500
++++ lib/CodeGen/CodeGenPrepare.cpp	2016-05-28 13:01:43.647551022 -0400
+@@ -2445,59 +2445,67 @@
+ 
+ private:
+   /// The ordered list of actions made so far.
+-  SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
+-  typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
++  /// You cannot use a SmallVector here because of copy vs. move
++  /// semantics. You can't use a std::unique_ptr eiter, for the
++  /// same exact reasons.
++  std::vector<std::shared_ptr<TypePromotionAction> > Actions;
++  typedef std::vector<std::shared_ptr<TypePromotionAction>>::iterator CommitPt;
+ };
+ 
+ void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
+                                           Value *NewVal) {
+   Actions.push_back(
+-      make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
++      std::make_shared<TypePromotionTransaction::OperandSetter>(Inst,
++                                                                Idx, NewVal));
+ }
+ 
+ void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
+                                                 Value *NewVal) {
+   Actions.push_back(
+-      make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
++      std::make_shared<TypePromotionTransaction::InstructionRemover>(Inst,
++                                                                     NewVal));
+ }
+ 
+ void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
+                                                   Value *New) {
+-  Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
++  Actions.push_back(
++    std::make_shared<TypePromotionTransaction::UsesReplacer>(Inst, New));
+ }
+ 
+ void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
+-  Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
++  Actions.push_back(
++    std::make_shared<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
+ }
+ 
+ Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
+                                              Type *Ty) {
+-  std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
++  std::shared_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
+   Value *Val = Ptr->getBuiltValue();
+-  Actions.push_back(std::move(Ptr));
++  Actions.push_back(Ptr);
+   return Val;
+ }
+ 
+ Value *TypePromotionTransaction::createSExt(Instruction *Inst,
+                                             Value *Opnd, Type *Ty) {
+-  std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
++  std::shared_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
+   Value *Val = Ptr->getBuiltValue();
+-  Actions.push_back(std::move(Ptr));
++  Actions.push_back(Ptr);
+   return Val;
+ }
+ 
+ Value *TypePromotionTransaction::createZExt(Instruction *Inst,
+                                             Value *Opnd, Type *Ty) {
+-  std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
++  std::shared_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
+   Value *Val = Ptr->getBuiltValue();
+-  Actions.push_back(std::move(Ptr));
++  Actions.push_back(Ptr);
+   return Val;
+ }
+ 
+ void TypePromotionTransaction::moveBefore(Instruction *Inst,
+                                           Instruction *Before) {
+   Actions.push_back(
+-      make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
++      std::make_shared<TypePromotionTransaction::InstructionMoveBefore>(Inst,
++                                                                        Before));
+ }
+ 
+ TypePromotionTransaction::ConstRestorationPt
+@@ -2515,8 +2523,9 @@
+ void TypePromotionTransaction::rollback(
+     TypePromotionTransaction::ConstRestorationPt Point) {
+   while (!Actions.empty() && Point != Actions.back().get()) {
+-    std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
++    std::shared_ptr<TypePromotionAction> Curr = Actions.back();
+     Curr->undo();
++    Actions.pop_back();
+   }
+ }
+ 
+###
+--- lib/CodeGen/Passes.cpp	2015-12-16 03:09:48.000000000 -0800
++++ lib/CodeGen/Passes.cpp	2016-05-13 17:38:47.747582295 -0700
+@@ -31,9 +31,17 @@
+ #include "llvm/Transforms/Instrumentation.h"
+ #include "llvm/Transforms/Scalar.h"
+ #include "llvm/Transforms/Utils/SymbolRewriter.h"
+-
++#include "llvm/LinkAllPasses.h"
+ using namespace llvm;
+ 
++//===----------------------------------------------------------------------===//
++/// See the file ${top_srcdir}/include/llvm/LinkAllPasses.h for the
++/// explanation of this hack.
++namespace llvm {
++    ForcePassLinking* ForcePassLinking::FPL = new llvm::ForcePassLinking();
++} // namespace llvm
++//===----------------------------------------------------------------------===//
++
+ static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
+     cl::desc("Disable Post Regalloc"));
+ static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
+###
+--- lib/CodeGen/TargetLoweringObjectFileImpl.cpp	2015-11-17 22:02:15.000000000 -0800
++++ lib/CodeGen/TargetLoweringObjectFileImpl.cpp	2016-05-25 14:26:17.415867207 -0700
+@@ -360,8 +360,10 @@
+   return DataRelROSection;
+ }
+ 
+-static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
+-                                              bool IsCtor, unsigned Priority,
++static MCSectionELF *getStaticStructorSection(MCContext &Ctx,
++                                              bool UseInitArray,
++                                              bool IsCtor,
++                                              unsigned Priority,
+                                               const MCSymbol *KeySym) {
+   std::string Name;
+   unsigned Type;
+@@ -379,21 +381,34 @@
+       Type = ELF::SHT_FINI_ARRAY;
+       Name = ".fini_array";
+     }
++
+     if (Priority != 65535) {
+       Name += '.';
+-      Name += utostr(Priority);
++      Name += std::to_string(Priority);
+     }
+   } else {
+-    // The default scheme is .ctor / .dtor, so we have to invert the priority
+-    // numbering.
+-    if (IsCtor)
+-      Name = ".ctors";
+-    else
+-      Name = ".dtors";
++    if (Ctx.getObjectFileInfo()->getTargetTriple().getOS() ==
++        llvm::Triple::Solaris) {
++      // on Solaris we use .inift/.fini because the Solaris linker
++      // can't handle .ctors/.dtors.
++      if (IsCtor)
++        Name = ".init";
++      else
++        Name = ".fini";
++    } else {
++      // The default scheme is .ctor / .dtor, so we have to invert the priority
++      // numbering.
++      if (IsCtor)
++        Name = ".ctors";
++      else
++        Name = ".dtors";
++    }
++
+     if (Priority != 65535) {
+       Name += '.';
+-      Name += utostr(65535 - Priority);
++      Name += std::to_string(65535 - Priority);
+     }
++
+     Type = ELF::SHT_PROGBITS;
+   }
+ 
+###
+
--- a/components/llvm/patches/002-Makefile.patch	Thu Jul 28 16:15:45 2016 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,15 +0,0 @@
-# Solaris autoconf-based build.
-# https://llvm.org/bugs/show_bug.cgi?id=24641
---- tools/llvm-shlib/Makefile	2014-07-31 23:16:03.000000000 -0700
-+++ tools/llvm-shlib/Makefile	2015-06-07 11:01:59.791190596 -0700
-@@ -71,7 +71,9 @@
- 
- ifeq ($(HOST_OS),SunOS)
-     # add -z allextract ahead of other libraries on Solaris
--    LLVMLibsOptions := -Wl,-z -Wl,allextract $(LLVMLibsOptions)
-+    LLVMLibsOptions := -Wl,-z -Wl,rescan -Wl,-z -Wl,allextract $(LLVMLibsOptions)
-+    LLVMLibsOptions += -Wl,-h -Wl,lib$(LIBRARYNAME)$(SHLIBEXT)
-+    LLVMLibsOptions += -Wl,-z -Wl,defaultextract -Wl,-z -Wl,defs
- endif
- 
- ifeq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW))
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/002-solaris-LLVM-libLLVMSupport.patch	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,5472 @@
+# 24314638 LLVM CommandLine subsystem is busted
+# 24314687 static initialization of optimization passes doesn't work as
+# intended
+# 3.9.X for upstream.
+--- include/llvm/Support/raw_ostream.h	2015-12-16 14:59:06.000000000 -0800
++++ include/llvm/Support/raw_ostream.h	2016-05-19 17:27:46.046422643 -0700
+@@ -35,7 +35,7 @@
+ /// output to a stream.  It does not support seeking, reopening, rewinding, line
+ /// buffered disciplines etc. It is a simple buffer that outputs
+ /// a chunk at a time.
+-class raw_ostream {
++class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) raw_ostream {
+ private:
+   void operator=(const raw_ostream &) = delete;
+   raw_ostream(const raw_ostream &) = delete;
+###
+--- lib/Support/raw_ostream.cpp	2016-01-11	15:33:03.000000000 -0800
++++ lib/Support/raw_ostream.cpp	2016-05-25	20:32:16.532306707 -0700
+@@ -20,7 +20,9 @@
+ #include "llvm/Support/ErrorHandling.h"
+ #include "llvm/Support/FileSystem.h"
+ #include "llvm/Support/Format.h"
++#include "llvm/Support/ManagedStatic.h"
+ #include "llvm/Support/MathExtras.h"
++#include "llvm/Support/Mutex.h"
+ #include "llvm/Support/Process.h"
+ #include "llvm/Support/Program.h"
+ #include <cctype>
+@@ -496,7 +498,7 @@
+   // Handle "-" as stdout. Note that when we do this, we consider ourself
+   // the owner of stdout. This means that we can do things like close the
+   // file descriptor when we're done and set the "binary" flag globally.
+-  if (Filename == "-") {
++  if (Filename == StringRef("-")) {
+     EC = std::error_code();
+     // If user requested binary then put stdout into binary mode if
+     // possible.
+@@ -515,38 +517,61 @@
+ 
+ raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC,
+                                sys::fs::OpenFlags Flags)
+-    : raw_fd_ostream(getFD(Filename, EC, Flags), true) {}
++  : raw_pwrite_stream(true), FD(-1), ShouldClose(false),
++  Error(false), pos(static_cast<uint64_t>(-1)), SupportsSeeking(false) {
++    this->FD = getFD(Filename, EC, Flags);
++    if (this->FD < 0 ) {
++      ShouldClose = false;
++      return;
++    }
++
++  // Get the starting position.
++  off_t loc = ::lseek(this->FD, 0, SEEK_CUR);
++#ifdef LLVM_ON_WIN32
++  // MSVCRT's _lseek(SEEK_CUR) doesn't return -1 for pipes.
++  sys::fs::file_status Status;
++  std::error_code EC = status(FD, Status);
++  SupportsSeeking = !EC && Status.type() == sys::fs::file_type::regular_file;
++#else
++  SupportsSeeking = loc != static_cast<off_t>(-1);
++#endif
++  if (!SupportsSeeking)
++    pos = 0ULL;
++  else
++    pos = static_cast<uint64_t>(loc);
++}
+ 
+ /// FD is the file descriptor that this writes to.  If ShouldClose is true, this
+ /// closes the file when the stream is destroyed.
+ raw_fd_ostream::raw_fd_ostream(int fd, bool shouldClose, bool unbuffered)
+     : raw_pwrite_stream(unbuffered), FD(fd), ShouldClose(shouldClose),
+-      Error(false) {
+-  if (FD < 0 ) {
++  Error(false), pos(static_cast<uint64_t>(-1)), SupportsSeeking(false) {
++  if (this->FD < 0 ) {
+     ShouldClose = false;
+     return;
+   }
+ 
+   // Get the starting position.
+-  off_t loc = ::lseek(FD, 0, SEEK_CUR);
++  off_t loc = ::lseek(this->FD, 0, SEEK_CUR);
+ #ifdef LLVM_ON_WIN32
+   // MSVCRT's _lseek(SEEK_CUR) doesn't return -1 for pipes.
+   sys::fs::file_status Status;
+   std::error_code EC = status(FD, Status);
+   SupportsSeeking = !EC && Status.type() == sys::fs::file_type::regular_file;
+ #else
+-  SupportsSeeking = loc != (off_t)-1;
++  SupportsSeeking = loc != static_cast<off_t>(-1);
+ #endif
+   if (!SupportsSeeking)
+-    pos = 0;
++    pos = 0ULL;
+   else
+     pos = static_cast<uint64_t>(loc);
+ }
+ 
+ raw_fd_ostream::~raw_fd_ostream() {
+-  if (FD >= 0) {
++  if (this->FD >= 0) {
+     flush();
+-    if (ShouldClose && sys::Process::SafelyCloseFileDescriptor(FD))
++
++    if (ShouldClose && sys::Process::SafelyCloseFileDescriptor(this->FD))
+       error_detected();
+   }
+ 
+@@ -585,7 +610,7 @@
+     if (ChunkSize > 32767 && ShouldWriteInChunks)
+         ChunkSize = 32767;
+ 
+-    ssize_t ret = ::write(FD, Ptr, ChunkSize);
++    ssize_t ret = ::write(this->FD, Ptr, ChunkSize);
+ 
+     if (ret < 0) {
+       // If it's a recoverable error, swallow it and retry the write.
+@@ -617,11 +642,14 @@
+ }
+ 
+ void raw_fd_ostream::close() {
+-  assert(ShouldClose);
++  if (FD == -1) {
++    ShouldClose = false;
++    return;
++  }
++
+   ShouldClose = false;
+   flush();
+-  if (sys::Process::SafelyCloseFileDescriptor(FD))
+-    error_detected();
++  (void) sys::Process::SafelyCloseFileDescriptor(FD);
+   FD = -1;
+ }
+ 
+@@ -715,30 +743,64 @@
+ //  outs(), errs(), nulls()
+ //===----------------------------------------------------------------------===//
+ 
++static raw_fd_ostream *SOUT = nullptr;
++static llvm::ManagedStatic<llvm::sys::SmartMutex<true> > SOutMutex;
++
++static raw_fd_ostream *SERR = nullptr;
++static llvm::ManagedStatic<llvm::sys::SmartMutex<true> > SErrMutex;
++
++static raw_null_ostream *SNULL = nullptr;
++static llvm::ManagedStatic<llvm::sys::SmartMutex<true> > SNullMutex;
++
+ /// outs() - This returns a reference to a raw_ostream for standard output.
+ /// Use it like: outs() << "foo" << "bar";
++__attribute__((noinline))
+ raw_ostream &llvm::outs() {
+   // Set buffer settings to model stdout behavior.
+   // Delete the file descriptor when the program exits, forcing error
+   // detection. If you don't want this behavior, don't use outs().
+-  std::error_code EC;
+-  static raw_fd_ostream S("-", EC, sys::fs::F_None);
+-  assert(!EC);
+-  return S;
++  // This makes absolutely no sense whatsoever. getFD returns STDOUT_FILENO
++  // anyway.
++
++  if (!SOUT) {
++    llvm::sys::SmartScopedLock<true> Lock(*SOutMutex);
++    if (!SOUT) {
++      SOUT = new raw_fd_ostream(STDOUT_FILENO, false, false);
++      assert(SOUT);
++    }
++  }
++
++  return *SOUT;
+ }
+ 
+ /// errs() - This returns a reference to a raw_ostream for standard error.
+ /// Use it like: errs() << "foo" << "bar";
++__attribute__((noinline))
+ raw_ostream &llvm::errs() {
+   // Set standard error to be unbuffered by default.
+-  static raw_fd_ostream S(STDERR_FILENO, false, true);
+-  return S;
++  if (!SERR) {
++    llvm::sys::SmartScopedLock<true> Lock(*SErrMutex);
++    if (!SERR) {
++      SERR = new raw_fd_ostream(STDERR_FILENO, false, true);
++      assert(SERR);
++    }
++  }
++
++  return *SERR;
+ }
+ 
+ /// nulls() - This returns a reference to a raw_ostream which discards output.
++__attribute__((noinline))
+ raw_ostream &llvm::nulls() {
+-  static raw_null_ostream S;
+-  return S;
++  if (!SNULL) {
++    llvm::sys::SmartScopedLock<true> Lock(*SNullMutex);
++    if (!SNULL) {
++      SNULL = new raw_null_ostream();
++      assert(SNULL);
++    }
++  }
++
++  return *SNULL;
+ }
+ 
+ 
+###
+--- include/llvm/Support/CommandLine.h	2015-11-17 10:00:52.000000000 -0900
++++ include/llvm/Support/CommandLine.h	2016-07-05 20:30:35.333194355 -0800
+@@ -25,11 +25,13 @@
+ #include "llvm/ADT/StringMap.h"
+ #include "llvm/ADT/Twine.h"
+ #include "llvm/Support/Compiler.h"
++#include "llvm/Support/raw_ostream.h"
+ #include <cassert>
+ #include <climits>
+ #include <cstdarg>
+ #include <utility>
+ #include <vector>
++#include <type_traits>
+ 
+ namespace llvm {
+ 
+@@ -111,7 +113,9 @@
+   // zero reserved for the unspecified value
+   ValueOptional = 0x01,  // The value can appear... or not
+   ValueRequired = 0x02,  // The value is required to appear!
+-  ValueDisallowed = 0x03 // A value may not be specified (for flags)
++  ValueDisallowed = 0x03,         // A value may not be specified (for flags)
++  ValuePositionalNoArgs = 0x04,   // Positional Argument, no additional args
++  ValuePositionalWithArgs = 0x05  // Positional Argument, with additional args
+ };
+ 
+ enum OptionHidden {   // Control whether -help shows this option
+@@ -149,6 +153,43 @@
+ };
+ 
+ //===----------------------------------------------------------------------===//
++// Generic Filename Locations
++//
++struct GenericFilenameLocation {
++  GenericFilenameLocation() : Value("") { }
++  GenericFilenameLocation(const std::string &S) : Value(S) { }
++  GenericFilenameLocation(std::string &&S)
++    : Value(std::move(S)) { }
++
++  void operator=(const std::string &S) {
++    if (!S.empty())
++      Value = S;
++  }
++
++  void operator=(std::string &&S) {
++    if (!S.empty())
++      Value = std::move(S);
++  }
++
++  std::string Value;
++};
++
++struct GenericFilenameLocations {
++  GenericFilenameLocations() : Value() { }
++  GenericFilenameLocations(const std::string &S)
++    : Value() {
++      Value.push_back(S);
++    }
++
++  void operator=(const std::string &S) {
++    if (!S.empty())
++      Value.push_back(S);
++  }
++
++  std::vector<std::string> Value;
++};
++
++//===----------------------------------------------------------------------===//
+ // Option Category class
+ //
+ class OptionCategory {
+@@ -176,6 +217,16 @@
+ class alias;
+ class Option {
+   friend class alias;
++  friend class OptionRegistry;
++
++protected:
++  /// RegisteredOptionList - This is the list of the command line options
++  /// that have statically constructed themselves.
++  static Option *RegisteredOptionList;
++
++  /// NumRegisteredOptions - The number of Options registered with the
++  /// RegisteredOptionList.
++  static unsigned NumRegisteredOptions;
+ 
+   // handleOccurrences - Overriden by subclasses to handle the value passed into
+   // an argument.  Should return true if there was an error processing the
+@@ -191,51 +242,65 @@
+   // Out of line virtual function to provide home for the class.
+   virtual void anchor();
+ 
+-  int NumOccurrences; // The number of times specified
++  // The number of times specified
++  int NumOccurrences;
++
+   // Occurrences, HiddenFlag, and Formatting are all enum types but to avoid
+   // problems with signed enums in bitfields.
+-  unsigned Occurrences : 3; // enum NumOccurrencesFlag
++  unsigned Occurrences; // enum NumOccurrencesFlag
++
++  // This Option's position index in the RegisteredOptionList.
++  // -1 means this option hasn't been registered.
++  int OptionIndex;
++
+   // not using the enum type for 'Value' because zero is an implementation
+   // detail representing the non-value
+-  unsigned Value : 2;
+-  unsigned HiddenFlag : 2; // enum OptionHidden
+-  unsigned Formatting : 2; // enum FormattingFlags
+-  unsigned Misc : 3;
++  unsigned Value;
++
++  unsigned HiddenFlag; // enum OptionHidden
++  unsigned Formatting; // enum FormattingFlags
++  unsigned Misc;
+   unsigned Position;       // Position of last occurrence of the option
+   unsigned AdditionalVals; // Greater than 0 for multi-valued option.
++  Option *NextRegistered;
+ 
+ public:
+-  StringRef ArgStr;   // The argument string itself (ex: "help", "o")
+-  StringRef HelpStr;  // The descriptive text message for -help
+-  StringRef ValueStr; // String describing what the value of this option is
++  const char *ArgStr;   // The argument string itself (ex: "help", "o")
++  const char *HelpStr;  // The descriptive text message for -help
++  const char *ValueStr; // String describing what the value of this option is
+   OptionCategory *Category; // The Category this option belongs to
+   bool FullyInitialized;    // Has addArguemnt been called?
+ 
+   inline enum NumOccurrencesFlag getNumOccurrencesFlag() const {
+-    return (enum NumOccurrencesFlag)Occurrences;
++    return static_cast<enum NumOccurrencesFlag>(Occurrences);
+   }
++
+   inline enum ValueExpected getValueExpectedFlag() const {
+-    return Value ? ((enum ValueExpected)Value) : getValueExpectedFlagDefault();
++    return Value ?
++      static_cast<enum ValueExpected>(Value) : getValueExpectedFlagDefault();
+   }
++
+   inline enum OptionHidden getOptionHiddenFlag() const {
+-    return (enum OptionHidden)HiddenFlag;
++    return static_cast<enum OptionHidden>(HiddenFlag);
+   }
++
+   inline enum FormattingFlags getFormattingFlag() const {
+-    return (enum FormattingFlags)Formatting;
++    return static_cast<enum FormattingFlags>(Formatting);
+   }
++
+   inline unsigned getMiscFlags() const { return Misc; }
+   inline unsigned getPosition() const { return Position; }
+   inline unsigned getNumAdditionalVals() const { return AdditionalVals; }
+ 
+   // hasArgStr - Return true if the argstr != ""
+-  bool hasArgStr() const { return !ArgStr.empty(); }
++  bool hasArgStr() const { return ArgStr && *ArgStr != '\0'; }
+ 
+   //-------------------------------------------------------------------------===
+   // Accessor functions set by OptionModifiers
+   //
+-  void setArgStr(StringRef S);
+-  void setDescription(StringRef S) { HelpStr = S; }
+-  void setValueStr(StringRef S) { ValueStr = S; }
++  void setArgStr(const char *S);
++  void setDescription(const char *S) { HelpStr = S; }
++  void setValueStr(const char *S) { ValueStr = S; }
+   void setNumOccurrencesFlag(enum NumOccurrencesFlag Val) { Occurrences = Val; }
+   void setValueExpectedFlag(enum ValueExpected Val) { Value = Val; }
+   void setHiddenFlag(enum OptionHidden Val) { HiddenFlag = Val; }
+@@ -245,16 +310,121 @@
+   void setCategory(OptionCategory &C) { Category = &C; }
+ 
+ protected:
++  Option() : NumOccurrences(0),
++  Occurrences(0),
++  OptionIndex(-1),
++  Value(0U),
++  HiddenFlag(0U),
++  Formatting(0U),
++  Misc(0U),
++  Position(0U),
++  AdditionalVals(0U),
++  NextRegistered(nullptr),
++  ArgStr(""),
++  HelpStr(""),
++  ValueStr(""),
++  Category(nullptr),
++  FullyInitialized(false) { }
++
+   explicit Option(enum NumOccurrencesFlag OccurrencesFlag,
+                   enum OptionHidden Hidden)
+-      : NumOccurrences(0), Occurrences(OccurrencesFlag), Value(0),
+-        HiddenFlag(Hidden), Formatting(NormalFormatting), Misc(0), Position(0),
+-        AdditionalVals(0), ArgStr(""), HelpStr(""), ValueStr(""),
+-        Category(&GeneralCategory), FullyInitialized(false) {}
++    : NumOccurrences(0),
++    Occurrences(OccurrencesFlag),
++    OptionIndex(-1),
++    Value(0U),
++    HiddenFlag(Hidden),
++    Formatting(NormalFormatting),
++    Misc(0U),
++    Position(0U),
++    AdditionalVals(0U),
++    NextRegistered(nullptr),
++    ArgStr(""),
++    HelpStr(""),
++    ValueStr(""),
++    Category(&GeneralCategory),
++    FullyInitialized(false) { }
+ 
+   inline void setNumAdditionalVals(unsigned n) { AdditionalVals = n; }
+ 
+ public:
++  Option(const Option &RHS)
++    : NumOccurrences(RHS.NumOccurrences),
++    Occurrences(RHS.Occurrences),
++    OptionIndex(RHS.OptionIndex),
++    Value(RHS.Value),
++    HiddenFlag(RHS.HiddenFlag),
++    Formatting(RHS.Formatting),
++    Misc(RHS.Misc),
++    Position(RHS.Position),
++    AdditionalVals(RHS.AdditionalVals),
++    NextRegistered(RHS.NextRegistered),
++    ArgStr(RHS.ArgStr),
++    HelpStr(RHS.HelpStr),
++    ValueStr(RHS.ValueStr),
++    Category(RHS.Category),
++    FullyInitialized(RHS.FullyInitialized)  { }
++
++  Option(Option &&RHS)
++    : NumOccurrences(std::move(RHS.NumOccurrences)),
++    Occurrences(std::move(RHS.Occurrences)),
++    OptionIndex(std::move(RHS.OptionIndex)),
++    Value(std::move(RHS.Value)),
++    HiddenFlag(std::move(RHS.HiddenFlag)),
++    Formatting(std::move(RHS.Formatting)),
++    Misc(std::move(RHS.Misc)),
++    Position(std::move(RHS.Position)),
++    AdditionalVals(std::move(RHS.AdditionalVals)),
++    NextRegistered(std::move(RHS.NextRegistered)),
++    ArgStr(std::move(RHS.ArgStr)),
++    HelpStr(std::move(RHS.HelpStr)),
++    ValueStr(std::move(RHS.ValueStr)),
++    Category(std::move(RHS.Category)),
++    FullyInitialized(std::move(RHS.FullyInitialized)) { }
++
++  Option &operator=(const Option &RHS) {
++    if (this != &RHS) {
++      NumOccurrences = RHS.NumOccurrences;
++      Occurrences = RHS.Occurrences;
++      OptionIndex = RHS.OptionIndex;
++      Value = RHS.Value;
++      HiddenFlag = RHS.HiddenFlag;
++      Formatting = RHS.Formatting;
++      Misc = RHS.Misc;
++      Position = RHS.Position;
++      AdditionalVals = RHS.AdditionalVals;
++      NextRegistered = RHS.NextRegistered;
++      ArgStr = RHS.ArgStr;
++      HelpStr = RHS.HelpStr;
++      ValueStr = RHS.ValueStr;
++      Category = RHS.Category;
++      FullyInitialized = RHS.FullyInitialized;
++    }
++
++    return *this;
++  }
++
++  const Option &operator=(Option &&RHS) {
++    if (this != &RHS) {
++      NumOccurrences = std::move(RHS.NumOccurrences);
++      Occurrences = std::move(RHS.Occurrences);
++      OptionIndex = RHS.OptionIndex;
++      Value = std::move(RHS.Value);
++      HiddenFlag = std::move(RHS.HiddenFlag);
++      Formatting = std::move(RHS.Formatting);
++      Misc = std::move(RHS.Misc);
++      Position = std::move(RHS.Position);
++      AdditionalVals = std::move(RHS.AdditionalVals);
++      NextRegistered = std::move(RHS.NextRegistered);
++      ArgStr = std::move(RHS.ArgStr);
++      HelpStr = std::move(RHS.HelpStr);
++      ValueStr = std::move(RHS.ValueStr);
++      Category = std::move(RHS.Category);
++      FullyInitialized = std::move(RHS.FullyInitialized);
++    }
++
++    return *this;
++  }
++
+   // addArgument - Register this argument with the commandline system.
+   //
+   void addArgument();
+@@ -265,6 +435,32 @@
+   /// For testing purposes only.
+   void removeArgument();
+ 
++  static void registerOption(Option *O) {
++    assert(O && "Invalid argument!");
++
++    O->NextRegistered = Option::RegisteredOptionList;
++    Option::RegisteredOptionList = O;
++    O->OptionIndex = Option::NumRegisteredOptions;
++    ++Option::NumRegisteredOptions;
++    O->FullyInitialized = true;
++  }
++
++  static Option *getRegisteredOptionList() {
++    return Option::RegisteredOptionList;
++  }
++
++  static unsigned getNumRegisteredOptions() {
++    return Option::NumRegisteredOptions;
++  }
++
++  virtual Option *getNextRegisteredOption() const {
++    if ((OptionIndex == -1) ||
++        (OptionIndex >= static_cast<int>(Option::NumRegisteredOptions)))
++      return nullptr;
++
++    return NextRegistered;
++  }
++
+   // Return the width of the option tag for printing...
+   virtual size_t getOptionWidth() const = 0;
+ 
+@@ -275,13 +471,17 @@
+ 
+   virtual void printOptionValue(size_t GlobalWidth, bool Force) const = 0;
+ 
+-  virtual void getExtraOptionNames(SmallVectorImpl<StringRef> &) {}
++  virtual void getExtraOptionNames(std::vector<const char*> &V) { }
+ 
+   // addOccurrence - Wrapper around handleOccurrence that enforces Flags.
+   //
+   virtual bool addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
+                              bool MultiArg = false);
+ 
++  // addOccurrence - Increment the NumOccurrences counter.
++  //
++  virtual void addOccurrence();
++
+   // Prints option name followed by message.  Always returns true.
+   bool error(const Twine &Message, StringRef ArgName = StringRef());
+ 
+@@ -298,6 +498,7 @@
+ // desc - Modifier to set the description shown in the -help output...
+ struct desc {
+   const char *Desc;
++  desc() : Desc("") { }
+   desc(const char *Str) : Desc(Str) {}
+   void apply(Option &O) const { O.setDescription(Desc); }
+ };
+@@ -306,6 +507,7 @@
+ // output...
+ struct value_desc {
+   const char *Desc;
++  value_desc() : Desc("") { }
+   value_desc(const char *Str) : Desc(Str) {}
+   void apply(Option &O) const { O.setValueStr(Desc); }
+ };
+@@ -314,29 +516,37 @@
+ // the default constructor for the argument type does not give you what you
+ // want.  This is only valid on "opt" arguments, not on "list" arguments.
+ //
+-template <class Ty> struct initializer {
++template<typename Ty> struct initializer {
+   const Ty &Init;
+   initializer(const Ty &Val) : Init(Val) {}
++  initializer(const initializer &RHS) : Init(RHS.Init) { }
++  initializer(initializer &&RHS) : Init(RHS.Init) { }
+ 
+-  template <class Opt> void apply(Opt &O) const { O.setInitialValue(Init); }
++  template <typename Opt> void apply(Opt &O) const { O.setInitialValue(Init); }
+ };
+ 
+-template <class Ty> initializer<Ty> init(const Ty &Val) {
+-  return initializer<Ty>(Val);
++template <typename Ty>
++initializer<Ty> init(const Ty &Val) {
++  llvm::cl::initializer<Ty> I(Val);
++  return I;
+ }
+ 
+ // location - Allow the user to specify which external variable they want to
+ // store the results of the command line argument processing into, if they don't
+ // want to store it in the option itself.
+ //
+-template <class Ty> struct LocationClass {
++template <typename Ty> struct LocationClass {
+   Ty &Loc;
++
+   LocationClass(Ty &L) : Loc(L) {}
++  LocationClass(const LocationClass &RHS) : Loc(RHS.Loc) { }
++  LocationClass(LocationClass &&RHS) : Loc(RHS.Loc) { }
+ 
+-  template <class Opt> void apply(Opt &O) const { O.setLocation(O, Loc); }
++  template <typename Opt>
++  void apply(Opt &O) const { O.setLocation(O, Loc); }
+ };
+ 
+-template <class Ty> LocationClass<Ty> location(Ty &L) {
++template <typename Ty> LocationClass<Ty> location(Ty &L) {
+   return LocationClass<Ty>(L);
+ }
+ 
+@@ -344,43 +554,62 @@
+ // to.
+ struct cat {
+   OptionCategory &Category;
+-  cat(OptionCategory &c) : Category(c) {}
+ 
+-  template <class Opt> void apply(Opt &O) const { O.setCategory(Category); }
++  cat(OptionCategory &C) : Category(C) { }
++  cat(const cat &RHS) : Category(RHS.Category) { }
++  virtual ~cat() { }
++
++  template<typename Opt>
++  void apply(Opt &O) const { O.setCategory(Category); }
+ };
+ 
+ //===----------------------------------------------------------------------===//
+ // OptionValue class
+ 
+ // Support value comparison outside the template.
+-struct GenericOptionValue {
++class GenericOptionValue {
++public:
+   virtual bool compare(const GenericOptionValue &V) const = 0;
+ 
+ protected:
+-  ~GenericOptionValue() = default;
+-  GenericOptionValue() = default;
+-  GenericOptionValue(const GenericOptionValue&) = default;
+-  GenericOptionValue &operator=(const GenericOptionValue &) = default;
++  virtual ~GenericOptionValue() { }
++  GenericOptionValue() { }
++  GenericOptionValue(const GenericOptionValue &RHS) { }
++  GenericOptionValue(GenericOptionValue &&RHS) { }
++  GenericOptionValue &operator=(const GenericOptionValue &RHS) {
++    return *this;
++  }
++
++  const GenericOptionValue &operator=(GenericOptionValue &&RHS) {
++    return *this;
++  }
+ 
+ private:
+   virtual void anchor();
+ };
+ 
+-template <class DataType> struct OptionValue;
++template<typename DataType, bool> class OptionValue;
+ 
+ // The default value safely does nothing. Option value printing is only
+ // best-effort.
+-template <class DataType, bool isClass>
+-struct OptionValueBase : public GenericOptionValue {
++template<typename DataType, bool isClass>
++class OptionValueBase : public GenericOptionValue {
++public:
+   // Temporary storage for argument passing.
+-  typedef OptionValue<DataType> WrapperType;
++  typedef OptionValue<DataType, false> WrapperType;
+ 
+   bool hasValue() const { return false; }
+ 
+-  const DataType &getValue() const { llvm_unreachable("no default value"); }
++  const DataType &getValue() const {
++    llvm::errs() << __PRETTY_FUNCTION__ << ": no default value!\n";
++    abort();
++  }
++
++  void setValue(const DataType &V) { }
+ 
+   // Some options may take their value from a different data type.
+-  template <class DT> void setValue(const DT & /*V*/) {}
++  template<typename DT>
++  void setValue(const DT &V) { }
+ 
+   bool compare(const DataType & /*V*/) const { return false; }
+ 
+@@ -389,21 +618,55 @@
+   }
+ 
+ protected:
+-  ~OptionValueBase() = default;
++  virtual ~OptionValueBase() { }
++
++public:
++  OptionValueBase() : GenericOptionValue() { }
+ };
+ 
+ // Simple copy of the option value.
+-template <class DataType> class OptionValueCopy : public GenericOptionValue {
++template<typename DataType>
++class OptionValueCopy : public GenericOptionValue {
++protected:
+   DataType Value;
+   bool Valid;
+ 
+-protected:
+-  ~OptionValueCopy() = default;
+-  OptionValueCopy(const OptionValueCopy&) = default;
+-  OptionValueCopy &operator=(const OptionValueCopy&) = default;
+-
+ public:
+-  OptionValueCopy() : Valid(false) {}
++  OptionValueCopy<DataType>()
++  : GenericOptionValue(), Value(), Valid(false) { }
++
++  OptionValueCopy<DataType>(const OptionValueCopy<DataType> &RHS)
++  : GenericOptionValue(RHS), Value(RHS.Value), Valid(RHS.Valid) { }
++
++  OptionValueCopy<DataType>&
++  operator=(const OptionValueCopy<DataType> &RHS) {
++    if (this != &RHS) {
++      GenericOptionValue::operator=(RHS);
++      Value = RHS.Value;
++      Valid = RHS.Valid;
++    }
++
++    return *this;
++  }
++
++  const OptionValueCopy<DataType>&
++  operator=(OptionValueCopy<DataType> &&RHS) {
++    if (this != &RHS) {
++      GenericOptionValue::operator=(RHS);
++      Value = std::move(RHS.Value);
++      Valid = std::move(RHS.Valid);
++    }
++
++    return *this;
++  }
++
++  OptionValueCopy<DataType> &operator=(const DataType& V) {
++    Value = V;
++    Valid = true;
++    return *this;
++  }
++
++  ~OptionValueCopy<DataType>() { }
+ 
+   bool hasValue() const { return Valid; }
+ 
+@@ -417,6 +680,12 @@
+     Value = V;
+   }
+ 
++  template<typename DT>
++  void setValue(const DT &V) {
++    Valid = true;
++    Value = V;
++  }
++
+   bool compare(const DataType &V) const { return Valid && (Value != V); }
+ 
+   bool compare(const GenericOptionValue &V) const override {
+@@ -429,117 +698,178 @@
+ };
+ 
+ // Non-class option values.
+-template <class DataType>
+-struct OptionValueBase<DataType, false> : OptionValueCopy<DataType> {
++template<typename DataType>
++class OptionValueBase<DataType, false> : public OptionValueCopy<DataType> {
++public:
+   typedef DataType WrapperType;
+ 
+ protected:
+-  ~OptionValueBase() = default;
+-  OptionValueBase() = default;
+-  OptionValueBase(const OptionValueBase&) = default;
+-  OptionValueBase &operator=(const OptionValueBase&) = default;
++  virtual ~OptionValueBase<DataType, false>() { }
++
++  OptionValueBase<DataType, false>()
++  : OptionValueCopy<DataType>() { }
++
++  OptionValueBase<DataType, false>(
++    const OptionValueBase<DataType, false> &RHS)
++  : OptionValueCopy<DataType>(RHS) { }
++
++  OptionValueBase<DataType, false>&
++  operator=(const OptionValueBase<DataType, false> &RHS) {
++    if (this != &RHS)
++      OptionValueCopy<DataType>::operator=(RHS);
++
++    return *this;
++  }
++
++  const OptionValueBase<DataType, false>&
++  operator=(OptionValueBase<DataType, false> &&RHS) {
++    if (this != &RHS)
++      OptionValueCopy<DataType>::operator=(RHS);
++
++    return *this;
++  }
++
++  void setValue(const DataType& V) {
++    OptionValueCopy<DataType>::setValue(V);
++  }
++
++  template<typename DT>
++  void setValue(const DT &V) {
++    OptionValueCopy<DataType>::setValue(V);
++  }
+ };
+ 
+ // Top-level option class.
+-template <class DataType>
+-struct OptionValue final
+-    : OptionValueBase<DataType, std::is_class<DataType>::value> {
+-  OptionValue() = default;
++template<typename DataType, bool IsClass = std::is_class<DataType>::value>
++class OptionValue final :
++  public OptionValueBase<DataType, std::is_class<DataType>::value> {
++public:
++  OptionValue<DataType, IsClass>()
++  : OptionValueBase<DataType, IsClass>() { }
++
++  OptionValue<DataType, IsClass>(const OptionValue<DataType, IsClass> &RHS)
++  : OptionValueBase<DataType, IsClass>(RHS) { }
++
++  OptionValue<DataType, IsClass>&
++  operator=(const OptionValue<DataType, IsClass> &RHS) {
++    if (this != &RHS) {
++      OptionValueBase<DataType, IsClass>::operator=(RHS);
++    }
++
++    return *this;
++  }
++
++  virtual ~OptionValue<DataType, IsClass>() { }
++
++  OptionValue<DataType, IsClass>(const DataType &V)
++  : OptionValueBase<DataType, IsClass>() {
++    OptionValueBase<DataType, IsClass>::setValue(V);
++  }
++
++  void setValue(const DataType &V) {
++    OptionValueBase<DataType, IsClass>::setValue(V);
++  }
++
++  template<typename DT>
++  void setValue(const DT &V) {
++    OptionValueBase<DataType, IsClass>::setValue(V);
++  }
+ 
+-  OptionValue(const DataType &V) { this->setValue(V); }
+   // Some options may take their value from a different data type.
+-  template <class DT> OptionValue<DataType> &operator=(const DT &V) {
+-    this->setValue(V);
++  template<typename DT>
++  OptionValue<DataType, IsClass> &operator=(const DT &V) {
++    // this->setValue(V);
++    OptionValueBase<DataType, IsClass>::setValue(V);
+     return *this;
+   }
+ };
+ 
+ // Other safe-to-copy-by-value common option types.
+ enum boolOrDefault { BOU_UNSET, BOU_TRUE, BOU_FALSE };
++
+ template <>
+-struct OptionValue<cl::boolOrDefault> final
+-    : OptionValueCopy<cl::boolOrDefault> {
++class OptionValue<cl::boolOrDefault> final
++    : public OptionValueCopy<cl::boolOrDefault> {
++public:
+   typedef cl::boolOrDefault WrapperType;
+ 
+-  OptionValue() {}
++  OptionValue<cl::boolOrDefault>()
++  : OptionValueCopy<cl::boolOrDefault>() { }
++
++  OptionValue<cl::boolOrDefault>(const OptionValue<cl::boolOrDefault> &RHS)
++  : OptionValueCopy<cl::boolOrDefault>(RHS) { }
++
++  OptionValue<cl::boolOrDefault>(const cl::boolOrDefault &V)
++  : OptionValueCopy<cl::boolOrDefault>() {
++    this->setValue(V);
++  }
+ 
+-  OptionValue(const cl::boolOrDefault &V) { this->setValue(V); }
+   OptionValue<cl::boolOrDefault> &operator=(const cl::boolOrDefault &V) {
+     setValue(V);
+     return *this;
+   }
+ 
++  OptionValue<cl::boolOrDefault>&
++  operator=(const OptionValue<cl::boolOrDefault> &RHS) {
++    if (this != &RHS) {
++      OptionValueCopy<cl::boolOrDefault>::operator=(RHS);
++      this->setValue(RHS.getValue());
++    }
++
++    return *this;
++  }
++
++  virtual ~OptionValue<cl::boolOrDefault>() { }
++
+ private:
+   void anchor() override;
+ };
+ 
+ template <>
+-struct OptionValue<std::string> final : OptionValueCopy<std::string> {
++class OptionValue<std::string> final : public OptionValueCopy<std::string> {
++public:
+   typedef StringRef WrapperType;
+ 
+-  OptionValue() {}
++  OptionValue<std::string>() : OptionValueCopy<std::string>() { }
++
++  OptionValue<std::string>(const OptionValue<std::string> &RHS)
++  : OptionValueCopy<std::string>(RHS) { }
++
++  OptionValue<std::string>(const std::string &V) {
++    this->setValue(V);
++  }
++
++  OptionValue<std::string>(std::string &&V) {
++    this->setValue(V);
++  }
+ 
+-  OptionValue(const std::string &V) { this->setValue(V); }
+   OptionValue<std::string> &operator=(const std::string &V) {
++    OptionValueCopy<std::string>::operator=(V);
+     setValue(V);
+     return *this;
+   }
+ 
+-private:
+-  void anchor() override;
+-};
+-
+-//===----------------------------------------------------------------------===//
+-// Enum valued command line option
+-//
+-#define clEnumVal(ENUMVAL, DESC) #ENUMVAL, int(ENUMVAL), DESC
+-#define clEnumValN(ENUMVAL, FLAGNAME, DESC) FLAGNAME, int(ENUMVAL), DESC
+-#define clEnumValEnd (reinterpret_cast<void *>(0))
+-
+-// values - For custom data types, allow specifying a group of values together
+-// as the values that go into the mapping that the option handler uses.  Note
+-// that the values list must always have a 0 at the end of the list to indicate
+-// that the list has ended.
+-//
+-template <class DataType> class ValuesClass {
+-  // Use a vector instead of a map, because the lists should be short,
+-  // the overhead is less, and most importantly, it keeps them in the order
+-  // inserted so we can print our option out nicely.
+-  SmallVector<std::pair<const char *, std::pair<int, const char *>>, 4> Values;
+-  void processValues(va_list Vals);
+-
+-public:
+-  ValuesClass(const char *EnumName, DataType Val, const char *Desc,
+-              va_list ValueArgs) {
+-    // Insert the first value, which is required.
+-    Values.push_back(std::make_pair(EnumName, std::make_pair(Val, Desc)));
+-
+-    // Process the varargs portion of the values...
+-    while (const char *enumName = va_arg(ValueArgs, const char *)) {
+-      DataType EnumVal = static_cast<DataType>(va_arg(ValueArgs, int));
+-      const char *EnumDesc = va_arg(ValueArgs, const char *);
+-      Values.push_back(std::make_pair(enumName, // Add value to value map
+-                                      std::make_pair(EnumVal, EnumDesc)));
+-    }
++  const OptionValue<std::string> &operator=(std::string &&V) {
++    OptionValueCopy<std::string>::operator=(V);
++    setValue(V);
++    return *this;
+   }
+ 
+-  template <class Opt> void apply(Opt &O) const {
+-    for (size_t i = 0, e = Values.size(); i != e; ++i)
+-      O.getParser().addLiteralOption(Values[i].first, Values[i].second.first,
+-                                     Values[i].second.second);
++  OptionValue<std::string> &operator=(const OptionValue<std::string> &RHS) {
++    if (this != &RHS) {
++      OptionValueCopy<std::string>::operator=(RHS);
++      setValue(RHS.getValue());
+   }
+-};
+ 
+-template <class DataType>
+-ValuesClass<DataType> LLVM_END_WITH_NULL
+-values(const char *Arg, DataType Val, const char *Desc, ...) {
+-  va_list ValueArgs;
+-  va_start(ValueArgs, Desc);
+-  ValuesClass<DataType> Vals(Arg, Val, Desc, ValueArgs);
+-  va_end(ValueArgs);
+-  return Vals;
++    return *this;
+ }
+ 
++  virtual ~OptionValue<std::string>() { }
++
++private:
++  void anchor() override;
++};
++
+ //===----------------------------------------------------------------------===//
+ // parser class - Parameterizable parser for different data types.  By default,
+ // known data types (string, int, bool) have specialized parsers, that do what
+@@ -556,20 +886,73 @@
+ protected:
+   class GenericOptionInfo {
+   public:
++    GenericOptionInfo() : Name(""), HelpStr("") { }
++
+     GenericOptionInfo(const char *name, const char *helpStr)
+         : Name(name), HelpStr(helpStr) {}
++
++    GenericOptionInfo(const GenericOptionInfo &RHS)
++      : Name(RHS.Name), HelpStr(RHS.HelpStr) { }
++
++    GenericOptionInfo(GenericOptionInfo &&RHS)
++      : Name(RHS.Name), HelpStr(RHS.HelpStr) { }
++
++    virtual ~GenericOptionInfo() { }
++
++    GenericOptionInfo &operator=(const GenericOptionInfo &RHS) {
++      if (this != &RHS) {
++        Name = RHS.Name;
++        HelpStr = RHS.HelpStr;
++      }
++
++      return *this;
++    }
++
++    const GenericOptionInfo &operator=(GenericOptionInfo &&RHS) {
++      if (this != &RHS) {
++        Name = std::move(RHS.Name);
++        HelpStr = std::move(RHS.HelpStr);
++      }
++
++      return *this;
++    }
++
+     const char *Name;
+     const char *HelpStr;
+   };
+ 
++  static Option *DefaultInvalidOption;
++
+ public:
+-  generic_parser_base(Option &O) : Owner(O) {}
++  generic_parser_base()
++  : Owner(generic_parser_base::DefaultInvalidOption) { }
++
++  generic_parser_base(Option &O) : Owner(&O) { }
++
++  generic_parser_base(const generic_parser_base &RHS)
++  : Owner(RHS.Owner) { }
++
++  generic_parser_base(generic_parser_base &&RHS)
++  : Owner(RHS.Owner) { }
++
++  virtual ~generic_parser_base() { }
++
++  generic_parser_base &operator=(const generic_parser_base &RHS) {
++    if (this != &RHS)
++      Owner = RHS.Owner;
++
++    return *this;
++  }
+ 
+-  virtual ~generic_parser_base() {} // Base class should have virtual-dtor
++  const generic_parser_base &operator=(generic_parser_base &&RHS) {
++    if (this != &RHS)
++      Owner = std::move(RHS.Owner);
++
++    return *this;
++  }
+ 
+   // getNumOptions - Virtual function implemented by generic subclass to
+   // indicate how many entries are in Values.
+-  //
+   virtual unsigned getNumOptions() const = 0;
+ 
+   // getOption - Return option name N.
+@@ -597,19 +980,27 @@
+   // Template definition ensures that the option and default have the same
+   // DataType (via the same AnyOptionValue).
+   template <class AnyOptionValue>
+-  void printOptionDiff(const Option &O, const AnyOptionValue &V,
++  void printOptionDiff(const Option &O,
++                       const AnyOptionValue &V,
+                        const AnyOptionValue &Default,
+                        size_t GlobalWidth) const {
+     printGenericOptionDiff(O, V, Default, GlobalWidth);
+   }
+ 
+-  void initialize() {}
++  virtual bool isValid() const {
++    return Owner != DefaultInvalidOption;
++  }
++
++  virtual void initialize() { }
++  virtual void initialize(Option *O) { Owner = O; }
++  virtual void initialize(Option &O) { Owner = &O; }
+ 
+-  void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) {
++  virtual void
++  getExtraOptionNames(std::vector<const char*> &OptionNames) {
+     // If there has been no argstr specified, that means that we need to add an
+     // argument for every possible option.  This ensures that our options are
+     // vectored to us.
+-    if (!Owner.hasArgStr())
++    if (!Owner->hasArgStr())
+       for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
+         OptionNames.push_back(getOption(i));
+   }
+@@ -626,7 +1017,7 @@
+     //
+     // If this is the case, we cannot allow a value.
+     //
+-    if (Owner.hasArgStr())
++    if (Owner->hasArgStr())
+       return ValueRequired;
+     else
+       return ValueDisallowed;
+@@ -638,7 +1029,7 @@
+   unsigned findOption(const char *Name);
+ 
+ protected:
+-  Option &Owner;
++  Option *Owner;
+ };
+ 
+ // Default parser implementation - This implementation depends on having a
+@@ -647,24 +1038,109 @@
+ // command line option for -help.  Because this is a simple mapping parser, the
+ // data type can be any unsupported type.
+ //
+-template <class DataType> class parser : public generic_parser_base {
++template<typename DataType>
++class parser : public generic_parser_base {
+ protected:
+   class OptionInfo : public GenericOptionInfo {
+   public:
+-    OptionInfo(const char *name, DataType v, const char *helpStr)
+-        : GenericOptionInfo(name, helpStr), V(v) {}
++    OptionInfo() : V() { }
++
++    OptionInfo(const char *Name, DataType DT, const char *HelpStr)
++      : GenericOptionInfo(Name, HelpStr), V(DT) { }
++
++    OptionInfo(const OptionInfo &RHS)
++      : GenericOptionInfo(RHS), V(RHS.V) { }
++
++    OptionInfo(OptionInfo &&RHS)
++      : GenericOptionInfo(RHS), V(RHS.V) { }
++
++    virtual ~OptionInfo() { }
++
++    OptionInfo &operator=(const OptionInfo &RHS) {
++      if (this != &RHS) {
++        GenericOptionInfo::operator=(RHS);
++        V = RHS.V;
++      }
++
++      return *this;
++    }
++
++    const OptionInfo &operator=(OptionInfo &&RHS) {
++      if (this != &RHS) {
++        GenericOptionInfo::operator=(RHS);
++        V = std::move(RHS.V);
++      }
++
++      return *this;
++    }
++
++    OptionInfo &operator=(const OptionValue<DataType> &RHS) {
++      V = RHS;
++      return *this;
++    }
++
++    const OptionInfo &operator=(OptionValue<DataType> &&RHS) {
++      V = std::move(RHS);
++      return *this;
++    }
++
+     OptionValue<DataType> V;
+   };
+-  SmallVector<OptionInfo, 8> Values;
++
++  std::vector<OptionInfo> Values;
+ 
+ public:
+-  parser(Option &O) : generic_parser_base(O) {}
++  parser<DataType>()
++  : generic_parser_base(), Values() { }
++
++  parser<DataType>(Option &O)
++  : generic_parser_base(O), Values() { }
++
++  parser<DataType>(const parser<DataType> &RHS)
++  : generic_parser_base(RHS), Values(RHS.Values) { }
++
++  parser<DataType>(parser<DataType> &&RHS)
++  : generic_parser_base(RHS), Values(RHS.Values) { }
++
++  virtual ~parser<DataType>() { }
++
++  parser<DataType> &operator=(const parser<DataType> &RHS) {
++    if (this != &RHS) {
++      generic_parser_base::operator=(RHS);
++      Values = RHS.Values;
++    }
++
++    return *this;
++  }
++
++  const parser<DataType> &operator=(parser<DataType> &&RHS) {
++    if (this != &RHS) {
++      generic_parser_base::operator=(RHS);
++      Values = std::move(RHS.Values);
++    }
++
++    return *this;
++  }
++
++  // Why is this needed.
+   typedef DataType parser_data_type;
+ 
+   // Implement virtual functions needed by generic_parser_base
+-  unsigned getNumOptions() const override { return unsigned(Values.size()); }
+-  const char *getOption(unsigned N) const override { return Values[N].Name; }
+-  const char *getDescription(unsigned N) const override {
++  virtual unsigned getNumOptions() const override {
++    return unsigned(Values.size());
++  }
++
++  virtual const char *getOption(unsigned N) const override {
++    if (N >= Values.size())
++      return 0UL;
++
++    return Values[N].Name;
++  }
++
++  virtual const char *getDescription(unsigned N) const override {
++    if (N >= Values.size())
++      return 0UL;
++
+     return Values[N].HelpStr;
+   }
+ 
+@@ -676,7 +1152,7 @@
+   // parse - Return true on error.
+   bool parse(Option &O, StringRef ArgName, StringRef Arg, DataType &V) {
+     StringRef ArgVal;
+-    if (Owner.hasArgStr())
++    if (Owner->hasArgStr())
+       ArgVal = Arg;
+     else
+       ArgVal = ArgName;
+@@ -690,38 +1166,128 @@
+     return O.error("Cannot find option named '" + ArgVal + "'!");
+   }
+ 
+-  /// addLiteralOption - Add an entry to the mapping table.
+-  ///
+-  template <class DT>
+-  void addLiteralOption(const char *Name, const DT &V, const char *HelpStr) {
+-    assert(findOption(Name) == Values.size() && "Option already exists!");
+-    OptionInfo X(Name, static_cast<DataType>(V), HelpStr);
+-    Values.push_back(X);
+-    AddLiteralOption(Owner, Name);
++  /// addLiteralOption - Add an entry to the mapping table.
++  ///
++  template <typename DT>
++  void addLiteralOption(const char *Name, const DT &V, const char *HelpStr) {
++    assert(findOption(Name) == Values.size() && "Option already exists!");
++    OptionInfo X(Name, static_cast<DataType>(V), HelpStr);
++    Values.push_back(X);
++    AddLiteralOption(*Owner, Name);
++  }
++
++  void addLiteralOption(const char *Name, const DataType &V,
++                        const char *HelpStr) {
++    assert(findOption(Name) == Values.size() && "Option already exists!");
++    OptionInfo X(Name, V, HelpStr);
++    Values.push_back(X);
++  }
++
++  /// removeLiteralOption - Remove the specified option.
++  ///
++  void removeLiteralOption(const char *Name) {
++    unsigned N = findOption(Name);
++    assert(N != Values.size() && "Option not found!");
++    Values.erase(Values.begin() + N);
++  }
++};
++
++
++//===----------------------------------------------------------------------===//
++// Enum valued command line option
++//
++#define clEnumVal(ENUMVAL, DESC) #ENUMVAL, int(ENUMVAL), DESC
++#define clEnumValN(ENUMVAL, FLAGNAME, DESC) FLAGNAME, int(ENUMVAL), DESC
++#define clEnumValEnd (reinterpret_cast<void *>(0))
++
++// values - For custom data types, allow specifying a group of values together
++// as the values that go into the mapping that the option handler uses.  Note
++// that the values list must always have a 0 at the end of the list to indicate
++// that the list has ended.
++//
++template<typename DataType>
++class ValuesClass {
++  // Use a vector instead of a map, because the lists should be short,
++  // the overhead is less, and most importantly, it keeps them in the order
++  // inserted so we can print our option out nicely.
++  std::vector<std::pair<const char*, std::pair<int, const char*> > > Values;
++  void processValues(va_list Vals);
++
++public:
++  ValuesClass<DataType>(const char *EnumName, DataType Val, const char *Desc,
++                        va_list ValueArgs)
++  : Values() {
++    // Insert the first value, which is required.
++    Values.push_back(std::make_pair(EnumName, std::make_pair(Val, Desc)));
++
++    // Process the varargs portion of the values...
++    while (const char *enumName = va_arg(ValueArgs, const char *)) {
++      DataType EnumVal = static_cast<DataType>(va_arg(ValueArgs, int));
++      const char *EnumDesc = va_arg(ValueArgs, const char *);
++
++      Values.push_back(std::make_pair(enumName, // Add value to value map
++                                      std::make_pair(EnumVal, EnumDesc)));
++    }
++  }
++
++  ValuesClass<DataType>(const ValuesClass<DataType> &RHS)
++    : Values(RHS.Values) { }
++
++  ValuesClass<DataType>(ValuesClass<DataType> &&RHS)
++    : Values(RHS.Values) { }
++
++  ValuesClass<DataType> &operator=(const ValuesClass<DataType> &RHS) {
++    if (this != &RHS)
++      Values.operator=(RHS.Values);
++
++    return *this;
++  }
++
++  const ValuesClass &operator=(ValuesClass<DataType> &&RHS) {
++    if (this != &RHS)
++      Values = std::move(RHS.Values);
++
++    return *this;
+   }
+ 
+-  /// removeLiteralOption - Remove the specified option.
+-  ///
+-  void removeLiteralOption(const char *Name) {
+-    unsigned N = findOption(Name);
+-    assert(N != Values.size() && "Option not found!");
+-    Values.erase(Values.begin() + N);
++  ~ValuesClass() { }
++
++  template<typename Opt>
++  void apply(Opt &O) const {
++    for (size_t i = 0, e = Values.size(); i != e; ++i) {
++      O.getParser().addLiteralOption(Values[i].first, Values[i].second.first,
++                                     Values[i].second.second);
++    }
+   }
+ };
+ 
++template<typename DataType>
++ValuesClass<DataType> LLVM_END_WITH_NULL
++values(const char *Arg, DataType Val, const char *Desc, ...) {
++  va_list ValueArgs;
++  va_start(ValueArgs, Desc);
++  ValuesClass<DataType> Vals(Arg, Val, Desc, ValueArgs);
++  va_end(ValueArgs);
++  return Vals;
++}
++
++//===----------------------------------------------------------------------===//
++
+ //--------------------------------------------------
+ // basic_parser - Super class of parsers to provide boilerplate code
+ //
+ class basic_parser_impl { // non-template implementation of basic_parser<t>
+ public:
++  basic_parser_impl() { }
+   basic_parser_impl(Option &) {}
+ 
++  virtual ~basic_parser_impl() { }
+ 
+   enum ValueExpected getValueExpectedFlagDefault() const {
+     return ValueRequired;
+   }
+ 
+-  void getExtraOptionNames(SmallVectorImpl<StringRef> &) {}
++  virtual void getExtraOptionNames(std::vector<const char*> &V) { }
+ 
+   void initialize() {}
+ 
+@@ -744,7 +1310,6 @@
+   virtual void anchor();
+ 
+ protected:
+-  ~basic_parser_impl() = default;
+   // A helper for basic_parser::printOptionDiff.
+   void printOptionName(const Option &O, size_t GlobalWidth) const;
+ };
+@@ -752,23 +1317,87 @@
+ // basic_parser - The real basic parser is just a template wrapper that provides
+ // a typedef for the provided data type.
+ //
+-template <class DataType> class basic_parser : public basic_parser_impl {
++template<typename DataType>
++class basic_parser : public basic_parser_impl {
+ public:
+-  basic_parser(Option &O) : basic_parser_impl(O) {}
++  basic_parser<DataType>() : basic_parser_impl(), Values() { }
++  basic_parser<DataType>(Option &O) : basic_parser_impl(O), Values() { }
++  virtual ~basic_parser<DataType>() { }
++
++  virtual unsigned getNumOptions() const {
++    return static_cast<unsigned>(Values.size());
++  }
++
++  virtual const char *getOption(unsigned I) {
++    assert(I < static_cast<unsigned>(Values.size()) &&
++           "Index is out-of-range!");
++    return Values[I].Name;
++  }
++
++  virtual const char *getDescription(unsigned I) {
++    assert(I < static_cast<unsigned>(Values.size()) &&
++           "Index is out-of-range!");
++    return Values[I].Help;
++  }
++
+   typedef DataType parser_data_type;
+   typedef OptionValue<DataType> OptVal;
+ 
+ protected:
+-  // Workaround Clang PR22793
+-  ~basic_parser() {}
++  template<typename SameDataType>
++  class OptionInfo {
++    public:
++      OptionInfo<SameDataType>()
++      : Name(""), Help(""), V() { }
++
++      OptionInfo<SameDataType>(const char *NameStr, SameDataType DT,
++                               const char *HelpStr)
++      : Name(NameStr), Help(HelpStr), V(DT) { }
++
++      OptionInfo<SameDataType>(const OptionInfo<SameDataType> &RHS)
++      : Name(RHS.Name), Help(RHS.Help), V(RHS.V) { }
++
++      OptionInfo<SameDataType>&
++      operator=(const OptionInfo<SameDataType> &RHS) {
++        if (this != &RHS) {
++          Name = RHS.Name;
++          Help = RHS.Help;
++          V = RHS.V;
++        }
++
++        return *this;
++      }
++
++      const OptionInfo<SameDataType>&
++      operator=(OptionInfo<SameDataType> &&RHS) {
++        if (this != &RHS) {
++          Name = std::move(RHS.Name);
++          Help = std::move(RHS.Help);
++          V = std::move(RHS.V);
++        }
++
++        return *this;
++      }
++
++      ~OptionInfo() { }
++
++      const char *Name;
++      const char *Help;
++      OptionValue<SameDataType> V;
++    };
++
++  std::vector<OptionInfo<DataType> > Values;
+ };
+ 
+ //--------------------------------------------------
+ // parser<bool>
+ //
+-template <> class parser<bool> final : public basic_parser<bool> {
++template<>
++class parser<bool> final : public basic_parser<bool> {
+ public:
+-  parser(Option &O) : basic_parser(O) {}
++  parser<bool>() : basic_parser<bool>() { }
++  parser<bool>(Option &O) : basic_parser<bool>(O) { }
++  virtual ~parser<bool>() { }
+ 
+   // parse - Return true on error.
+   bool parse(Option &O, StringRef ArgName, StringRef Arg, bool &Val);
+@@ -782,21 +1411,25 @@
+   // getValueName - Do not print =<value> at all.
+   const char *getValueName() const override { return nullptr; }
+ 
+-  void printOptionDiff(const Option &O, bool V, OptVal Default,
++  void printOptionDiff(const Option &O, const bool &V,
++                       const llvm::cl::OptionValue<bool> &Default,
+                        size_t GlobalWidth) const;
+ 
+   // An out-of-line virtual method to provide a 'home' for this class.
+-  void anchor() override;
++  virtual void anchor() override;
+ };
+ 
+-extern template class basic_parser<bool>;
++// extern template class basic_parser<bool>;
+ 
+ //--------------------------------------------------
+ // parser<boolOrDefault>
+ template <>
+ class parser<boolOrDefault> final : public basic_parser<boolOrDefault> {
+ public:
+-  parser(Option &O) : basic_parser(O) {}
++
++  parser<boolOrDefault>() : basic_parser<boolOrDefault>() { }
++  parser<boolOrDefault>(Option &O) : basic_parser<boolOrDefault>(O) { }
++  virtual ~parser<boolOrDefault>() { }
+ 
+   // parse - Return true on error.
+   bool parse(Option &O, StringRef ArgName, StringRef Arg, boolOrDefault &Val);
+@@ -808,21 +1441,25 @@
+   // getValueName - Do not print =<value> at all.
+   const char *getValueName() const override { return nullptr; }
+ 
+-  void printOptionDiff(const Option &O, boolOrDefault V, OptVal Default,
++  void printOptionDiff(const Option &O, const boolOrDefault &V,
++                       const llvm::cl::OptionValue<boolOrDefault> &Default,
+                        size_t GlobalWidth) const;
+ 
+   // An out-of-line virtual method to provide a 'home' for this class.
+-  void anchor() override;
++  virtual void anchor() override;
+ };
+ 
+-extern template class basic_parser<boolOrDefault>;
++// extern template class basic_parser<boolOrDefault>;
+ 
+ //--------------------------------------------------
+ // parser<int>
+ //
+-template <> class parser<int> final : public basic_parser<int> {
++template<>
++class parser<int> final : public basic_parser<int> {
+ public:
+-  parser(Option &O) : basic_parser(O) {}
++  parser<int>() : basic_parser<int>() { }
++  parser<int>(Option &O) : basic_parser<int>(O) { }
++  virtual ~parser<int>() { }
+ 
+   // parse - Return true on error.
+   bool parse(Option &O, StringRef ArgName, StringRef Arg, int &Val);
+@@ -830,21 +1467,29 @@
+   // getValueName - Overload in subclass to provide a better default value.
+   const char *getValueName() const override { return "int"; }
+ 
+-  void printOptionDiff(const Option &O, int V, OptVal Default,
++  void addLiteralOption(const char *Name, int V, const char *HelpStr) {
++    OptionInfo<int> OI(Name, V, HelpStr);
++    Values.push_back(OI);
++  }
++
++  void printOptionDiff(const Option &O, const int &V,
++                       const llvm::cl::OptionValue<int> &Default,
+                        size_t GlobalWidth) const;
+ 
+   // An out-of-line virtual method to provide a 'home' for this class.
+-  void anchor() override;
++  virtual void anchor() override;
+ };
+ 
+-extern template class basic_parser<int>;
++// extern template class basic_parser<int>;
+ 
+ //--------------------------------------------------
+ // parser<unsigned>
+ //
+ template <> class parser<unsigned> final : public basic_parser<unsigned> {
+ public:
+-  parser(Option &O) : basic_parser(O) {}
++  parser<unsigned>() : basic_parser<unsigned>() { }
++  parser<unsigned>(Option &O) : basic_parser<unsigned>(O) { }
++  virtual ~parser<unsigned>() { }
+ 
+   // parse - Return true on error.
+   bool parse(Option &O, StringRef ArgName, StringRef Arg, unsigned &Val);
+@@ -852,14 +1497,20 @@
+   // getValueName - Overload in subclass to provide a better default value.
+   const char *getValueName() const override { return "uint"; }
+ 
+-  void printOptionDiff(const Option &O, unsigned V, OptVal Default,
++  void addLiteralOption(const char *Name, unsigned V, const char *HelpStr) {
++    OptionInfo<unsigned> OI(Name, V, HelpStr);
++    Values.push_back(OI);
++  }
++
++  void printOptionDiff(const Option &O, const unsigned &V,
++                       const llvm::cl::OptionValue<unsigned> &Default,
+                        size_t GlobalWidth) const;
+ 
+   // An out-of-line virtual method to provide a 'home' for this class.
+-  void anchor() override;
++  virtual void anchor() override;
+ };
+ 
+-extern template class basic_parser<unsigned>;
++// extern template class basic_parser<unsigned>;
+ 
+ //--------------------------------------------------
+ // parser<unsigned long long>
+@@ -868,7 +1519,10 @@
+ class parser<unsigned long long> final
+     : public basic_parser<unsigned long long> {
+ public:
+-  parser(Option &O) : basic_parser(O) {}
++  parser<unsigned long long>() : basic_parser<unsigned long long>() { }
++  parser<unsigned long long>(Option &O)
++    : basic_parser<unsigned long long>(O) { }
++  virtual ~parser<unsigned long long>() { }
+ 
+   // parse - Return true on error.
+   bool parse(Option &O, StringRef ArgName, StringRef Arg,
+@@ -877,21 +1531,31 @@
+   // getValueName - Overload in subclass to provide a better default value.
+   const char *getValueName() const override { return "uint"; }
+ 
+-  void printOptionDiff(const Option &O, unsigned long long V, OptVal Default,
++  void addLiteralOption(const char *Name, unsigned long long V,
++                        const char *HelpStr) {
++    OptionInfo<unsigned long long> OI(Name, V, HelpStr);
++    Values.push_back(OI);
++  }
++
++  void printOptionDiff(const Option &O, const unsigned long long &V,
++                       const llvm::cl::OptionValue<unsigned long long> &Default,
+                        size_t GlobalWidth) const;
+ 
+   // An out-of-line virtual method to provide a 'home' for this class.
+   void anchor() override;
+ };
+ 
+-extern template class basic_parser<unsigned long long>;
++// extern template class basic_parser<unsigned long long>;
+ 
+ //--------------------------------------------------
+ // parser<double>
+ //
+-template <> class parser<double> final : public basic_parser<double> {
++template<>
++class parser<double> final : public basic_parser<double> {
+ public:
+-  parser(Option &O) : basic_parser(O) {}
++  parser<double>() : basic_parser<double>() { }
++  parser<double>(Option &O) : basic_parser<double>(O) { }
++  virtual ~parser<double>() { }
+ 
+   // parse - Return true on error.
+   bool parse(Option &O, StringRef ArgName, StringRef Arg, double &Val);
+@@ -899,21 +1563,31 @@
+   // getValueName - Overload in subclass to provide a better default value.
+   const char *getValueName() const override { return "number"; }
+ 
+-  void printOptionDiff(const Option &O, double V, OptVal Default,
++  void addLiteralOption(const char *Name, double V,
++                        const char *HelpStr) {
++    OptionInfo<double> OI(Name, V, HelpStr);
++    Values.push_back(OI);
++  }
++
++  void printOptionDiff(const Option &O, const double &V,
++                       const llvm::cl::OptionValue<double> &Default,
+                        size_t GlobalWidth) const;
+ 
+   // An out-of-line virtual method to provide a 'home' for this class.
+-  void anchor() override;
++  virtual void anchor() override;
+ };
+ 
+-extern template class basic_parser<double>;
++// extern template class basic_parser<double>;
+ 
+ //--------------------------------------------------
+ // parser<float>
+ //
+-template <> class parser<float> final : public basic_parser<float> {
++template<>
++class parser<float> final : public basic_parser<float> {
+ public:
+-  parser(Option &O) : basic_parser(O) {}
++  parser<float>() : basic_parser<float>() { }
++  parser<float>(Option &O) : basic_parser<float>(O) { }
++  virtual ~parser<float>() { }
+ 
+   // parse - Return true on error.
+   bool parse(Option &O, StringRef ArgName, StringRef Arg, float &Val);
+@@ -921,21 +1595,31 @@
+   // getValueName - Overload in subclass to provide a better default value.
+   const char *getValueName() const override { return "number"; }
+ 
+-  void printOptionDiff(const Option &O, float V, OptVal Default,
++  void addLiteralOption(const char *Name, float V,
++                        const char *HelpStr) {
++    OptionInfo<float> OI(Name, V, HelpStr);
++    Values.push_back(OI);
++  }
++
++  void printOptionDiff(const Option &O, const float &V,
++                       const llvm::cl::OptionValue<float> &Default,
+                        size_t GlobalWidth) const;
+ 
+   // An out-of-line virtual method to provide a 'home' for this class.
+-  void anchor() override;
++  virtual void anchor() override;
+ };
+ 
+-extern template class basic_parser<float>;
++// extern template class basic_parser<float>;
+ 
+ //--------------------------------------------------
+ // parser<std::string>
+ //
+-template <> class parser<std::string> final : public basic_parser<std::string> {
++template<>
++class parser<std::string> final : public basic_parser<std::string> {
+ public:
+-  parser(Option &O) : basic_parser(O) {}
++  parser<std::string>() : basic_parser<std::string>() { }
++  parser<std::string>(Option &O) : basic_parser<std::string>(O) {}
++  virtual ~parser<std::string>() { }
+ 
+   // parse - Return true on error.
+   bool parse(Option &, StringRef, StringRef Arg, std::string &Value) {
+@@ -946,21 +1630,31 @@
+   // getValueName - Overload in subclass to provide a better default value.
+   const char *getValueName() const override { return "string"; }
+ 
+-  void printOptionDiff(const Option &O, StringRef V, OptVal Default,
++  void addLiteralOption(const char *Name, const std::string &V,
++                        const char *HelpStr) {
++    OptionInfo<std::string> OI(Name, V, HelpStr);
++    Values.push_back(OI);
++  }
++
++  void printOptionDiff(const Option &O, const std::string &V,
++                       const llvm::cl::OptionValue<std::string> &Default,
+                        size_t GlobalWidth) const;
+ 
+   // An out-of-line virtual method to provide a 'home' for this class.
+-  void anchor() override;
++  virtual void anchor() override;
+ };
+ 
+-extern template class basic_parser<std::string>;
++// extern template class basic_parser<std::string>;
+ 
+ //--------------------------------------------------
+ // parser<char>
+ //
+-template <> class parser<char> final : public basic_parser<char> {
++template<>
++class parser<char> final : public basic_parser<char> {
+ public:
++  parser<char>() : basic_parser<char>() { }
+   parser(Option &O) : basic_parser(O) {}
++  virtual ~parser<char>() { }
+ 
+   // parse - Return true on error.
+   bool parse(Option &, StringRef, StringRef Arg, char &Value) {
+@@ -971,14 +1665,20 @@
+   // getValueName - Overload in subclass to provide a better default value.
+   const char *getValueName() const override { return "char"; }
+ 
+-  void printOptionDiff(const Option &O, char V, OptVal Default,
++  void addLiteralOption(const char *Name, char V, const char *HelpStr) {
++    OptionInfo<char> OI(Name, V, HelpStr);
++    Values.push_back(OI);
++  }
++
++  void printOptionDiff(const Option &O, const char &V,
++                       const llvm::cl::OptionValue<char> &Default,
+                        size_t GlobalWidth) const;
+ 
+   // An out-of-line virtual method to provide a 'home' for this class.
+-  void anchor() override;
++  virtual void anchor() override;
+ };
+ 
+-extern template class basic_parser<char>;
++// extern template class basic_parser<char>;
+ 
+ //--------------------------------------------------
+ // PrintOptionDiff
+@@ -987,16 +1687,18 @@
+ // parser to handle all the template nastiness.
+ 
+ // This overloaded function is selected by the generic parser.
+-template <class ParserClass, class DT>
+-void printOptionDiff(const Option &O, const generic_parser_base &P, const DT &V,
+-                     const OptionValue<DT> &Default, size_t GlobalWidth) {
++template<typename ParserClass, typename DT>
++void printOptionDiff(const Option &O, const generic_parser_base &P,
++                     const DT &V, const OptionValue<DT> &Default,
++                     size_t GlobalWidth) {
+   OptionValue<DT> OV = V;
+   P.printOptionDiff(O, OV, Default, GlobalWidth);
+ }
+ 
+ // This is instantiated for basic parsers when the parsed value has a different
+ // type than the option value. e.g. HelpPrinter.
+-template <class ParserDT, class ValDT> struct OptionDiffPrinter {
++template<typename ParserDT, typename ValDT>
++struct OptionDiffPrinter {
+   void print(const Option &O, const parser<ParserDT> &P, const ValDT & /*V*/,
+              const OptionValue<ValDT> & /*Default*/, size_t GlobalWidth) {
+     P.printOptionNoValue(O, GlobalWidth);
+@@ -1005,7 +1707,8 @@
+ 
+ // This is instantiated for basic parsers when the parsed value has the same
+ // type as the option value.
+-template <class DT> struct OptionDiffPrinter<DT, DT> {
++template<typename DT>
++struct OptionDiffPrinter<DT, DT> {
+   void print(const Option &O, const parser<DT> &P, const DT &V,
+              const OptionValue<DT> &Default, size_t GlobalWidth) {
+     P.printOptionDiff(O, V, Default, GlobalWidth);
+@@ -1014,11 +1717,11 @@
+ 
+ // This overloaded function is selected by the basic parser, which may parse a
+ // different type than the option type.
+-template <class ParserClass, class ValDT>
+-void printOptionDiff(
+-    const Option &O,
++template<typename ParserClass, typename ValDT>
++void printOptionDiff(const Option &O,
+     const basic_parser<typename ParserClass::parser_data_type> &P,
+-    const ValDT &V, const OptionValue<ValDT> &Default, size_t GlobalWidth) {
++                     const ValDT &V, const OptionValue<ValDT> &Default,
++                     size_t GlobalWidth) {
+ 
+   OptionDiffPrinter<typename ParserClass::parser_data_type, ValDT> printer;
+   printer.print(O, static_cast<const ParserClass &>(P), V, Default,
+@@ -1031,53 +1734,70 @@
+ // not correctly respond to the apply method).  Because the syntax to use this
+ // is a pain, we have the 'apply' method below to handle the nastiness...
+ //
+-template <class Mod> struct applicator {
+-  template <class Opt> static void opt(const Mod &M, Opt &O) { M.apply(O); }
++template<typename Mod>
++struct applicator {
++  template<typename Opt>
++  static void opt(const Mod &M, Opt &O) { M.apply(O); }
+ };
+ 
+ // Handle const char* as a special case...
+-template <unsigned n> struct applicator<char[n]> {
+-  template <class Opt> static void opt(const char *Str, Opt &O) {
++template<unsigned N>
++struct applicator<char[N]> {
++  template <typename Opt> static void opt(const char *Str, Opt &O) {
+     O.setArgStr(Str);
+   }
+ };
+-template <unsigned n> struct applicator<const char[n]> {
++
++template<unsigned N>
++struct applicator<const char[N]> {
+   template <class Opt> static void opt(const char *Str, Opt &O) {
+     O.setArgStr(Str);
+   }
+ };
+-template <> struct applicator<const char *> {
++
++template<>
++struct applicator<const char *> {
+   template <class Opt> static void opt(const char *Str, Opt &O) {
+     O.setArgStr(Str);
+   }
+ };
+ 
+-template <> struct applicator<NumOccurrencesFlag> {
++template<>
++struct applicator<NumOccurrencesFlag> {
+   static void opt(NumOccurrencesFlag N, Option &O) {
+     O.setNumOccurrencesFlag(N);
+   }
+ };
+-template <> struct applicator<ValueExpected> {
++
++template<>
++struct applicator<ValueExpected> {
+   static void opt(ValueExpected VE, Option &O) { O.setValueExpectedFlag(VE); }
+ };
+-template <> struct applicator<OptionHidden> {
++
++template<>
++struct applicator<OptionHidden> {
+   static void opt(OptionHidden OH, Option &O) { O.setHiddenFlag(OH); }
+ };
+-template <> struct applicator<FormattingFlags> {
++
++template<>
++struct applicator<FormattingFlags> {
+   static void opt(FormattingFlags FF, Option &O) { O.setFormattingFlag(FF); }
+ };
+-template <> struct applicator<MiscFlags> {
++
++template<>
++struct applicator<MiscFlags> {
+   static void opt(MiscFlags MF, Option &O) { O.setMiscFlag(MF); }
+ };
+ 
+ // apply method - Apply modifiers to an option in a type safe way.
+-template <class Opt, class Mod, class... Mods>
++template<typename Opt, typename Mod, typename... Mods>
+ void apply(Opt *O, const Mod &M, const Mods &... Ms) {
+   applicator<Mod>::opt(M, *O);
+   apply(O, Ms...);
+ }
+ 
+-template <class Opt, class Mod> void apply(Opt *O, const Mod &M) {
++template<typename Opt, typename Mod>
++void apply(Opt *O, const Mod &M) {
+   applicator<Mod>::opt(M, *O);
+ }
+ 
+@@ -1088,39 +1808,101 @@
+ // assumes the user will specify a variable to store the data into with the
+ // cl::location(x) modifier.
+ //
+-template <class DataType, bool ExternalStorage, bool isClass>
+-class opt_storage {
++template<typename DataType, bool ExternalStorage, bool isClass>
++class LLVM_ALIGNAS(8) opt_storage {
++private:
+   DataType *Location; // Where to store the object...
+   OptionValue<DataType> Default;
+ 
++protected:
+   void check_location() const {
+     assert(Location && "cl::location(...) not specified for a command "
+                        "line option with external storage, "
+                        "or cl::init specified before cl::location()!!");
++    if (!Location) {
++      llvm::errs() << __PRETTY_FUNCTION__
++        << ": cl::location(...) not specified for a command "
++        << "line option with external storage, "
++        << "or cl::init specified before cl::location()!!\n";
++      abort();
++    }
+   }
+ 
+ public:
+-  opt_storage() : Location(nullptr) {}
++  opt_storage<DataType, ExternalStorage, isClass>()
++    : Location(nullptr), Default() { }
++
++  opt_storage<DataType, ExternalStorage, isClass>(
++    const opt_storage<DataType, ExternalStorage, isClass> &RHS)
++    : Location(RHS.Location), Default(RHS.Default) { }
++
++  opt_storage<DataType, ExternalStorage, isClass>(
++    opt_storage<DataType, ExternalStorage, isClass> &&RHS)
++    : Location(RHS.Location), Default(RHS.Default) { }
++
++  virtual ~opt_storage<DataType, ExternalStorage, isClass>() { }
++
++  opt_storage<DataType, ExternalStorage, isClass>&
++  operator=(const opt_storage<DataType, ExternalStorage, isClass> &RHS) {
++    if (this != &RHS) {
++      Location = RHS.Location;
++      Default = RHS.Default;
++    }
++
++    return *this;
++  }
++
++  const opt_storage<DataType, ExternalStorage, isClass>&
++  operator=(opt_storage<DataType, ExternalStorage, isClass> &&RHS) {
++    if (this != &RHS) {
++      Location = std::move(RHS.Location);
++      Default = std::move(RHS.Default);
++    }
++
++    return *this;
++  }
+ 
+   bool setLocation(Option &O, DataType &L) {
+     if (Location)
+       return O.error("cl::location(x) specified more than once!");
++
+     Location = &L;
+     Default = L;
+     return false;
+   }
+ 
+-  template <class T> void setValue(const T &V, bool initial = false) {
++  void setValue(const DataType &V, bool initial = false) {
+     check_location();
+-    *Location = V;
+-    if (initial)
++
++    DataType *DT =
++      reinterpret_cast<DataType*>(
++        const_cast<void*>(reinterpret_cast<const void*>(&V)));
++    Location = DT;
++
++    if (initial) {
++      Default = V;
++    }
++  }
++
++  template<typename T>
++  void setValue(const T &V, bool initial = false) {
++    check_location();
++
++    DataType *DT =
++      reinterpret_cast<DataType*>(
++        const_cast<void*>(reinterpret_cast<const void*>(&V)));
++    Location = DT;
++
++    if (initial) {
+       Default = V;
++    }
+   }
+ 
+   DataType &getValue() {
+     check_location();
+     return *Location;
+   }
++
+   const DataType &getValue() const {
+     check_location();
+     return *Location;
+@@ -1134,14 +1916,66 @@
+ // Define how to hold a class type object, such as a string.  Since we can
+ // inherit from a class, we do so.  This makes us exactly compatible with the
+ // object in all cases that it is used.
+-//
+-template <class DataType>
+-class opt_storage<DataType, false, true> : public DataType {
++template<typename DataType>
++class LLVM_ALIGNAS(8) opt_storage<DataType, false, true> : public DataType {
+ public:
++  DataType *Location;
+   OptionValue<DataType> Default;
+ 
+-  template <class T> void setValue(const T &V, bool initial = false) {
++  opt_storage<DataType, false, true>()
++  : DataType(), Location(nullptr), Default() { }
++
++  opt_storage<DataType, false, true>(
++    const opt_storage<DataType, false, true> &RHS)
++  : DataType(RHS), Location(RHS.Location), Default(RHS.Default) { }
++
++  opt_storage<DataType, false, true>(opt_storage<DataType, false, true> &&RHS)
++  : DataType(RHS), Location(RHS.Location),  Default(RHS.Default) { }
++
++  virtual ~opt_storage<DataType, false, true>() { }
++
++  opt_storage<DataType, false, true>
++  &operator=(const opt_storage<DataType, false, true> &RHS) {
++    if (this != &RHS) {
++      DataType::operator=(RHS);
++      Location = RHS.Location;
++      Default = RHS.Default;
++    }
++
++    return *this;
++  }
++
++  const opt_storage<DataType, false, true>
++  &operator=(opt_storage<DataType, false, true> &&RHS) {
++    if (this != &RHS) {
++      DataType::operator=(RHS);
++      Location = std::move(RHS.Location);
++      Default = std::move(RHS.Default);
++    }
++
++    return *this;
++  }
++
++  bool setLocation(Option &O, DataType &L) {
++    if (Location)
++      return O.error("cl::location(x) specified more than once!");
++
++    Location = &L;
++    Default = L;
++    return false;
++  }
++
++  void setValue(const DataType &V, bool initial = false) {
+     DataType::operator=(V);
++
++    if (initial)
++      Default = V;
++  }
++
++  template<typename T>
++  void setValue(const T &V, bool initial = false) {
++    DataType::operator=(V);
++
+     if (initial)
+       Default = V;
+   }
+@@ -1155,27 +1989,68 @@
+ // Define a partial specialization to handle things we cannot inherit from.  In
+ // this case, we store an instance through containment, and overload operators
+ // to get at the value.
+-//
+-template <class DataType> class opt_storage<DataType, false, false> {
++template<typename DataType>
++class LLVM_ALIGNAS(8) opt_storage<DataType, false, false> {
+ public:
+   DataType Value;
+   OptionValue<DataType> Default;
+ 
+   // Make sure we initialize the value with the default constructor for the
+   // type.
+-  opt_storage() : Value(DataType()), Default(DataType()) {}
++  opt_storage<DataType, false, false>() : Value(), Default() { }
++
++  opt_storage<DataType, false, false>(
++    const opt_storage<DataType, false, false> &RHS)
++  : Value(RHS.Value), Default(RHS.Default) { }
++
++  opt_storage<DataType, false, false>(opt_storage<DataType, false, false> &&RHS)
++  : Value(std::move(RHS.Value)), Default(std::move(RHS.Default)) { }
++
++  opt_storage<DataType, false, false>
++  &operator=(const opt_storage<DataType, false, false> &RHS) {
++      if (this != &RHS) {
++        Value = RHS.Value;
++        Default = RHS.Default;
++      }
++
++      return *this;
++    }
++
++  const opt_storage<DataType, false, false>
++  &operator=(opt_storage<DataType, false, false> &&RHS) {
++      if (this != &RHS) {
++        Value = std::move(RHS.Value);
++        Default = std::move(RHS.Default);
++      }
++
++      return *this;
++    }
+ 
+-  template <class T> void setValue(const T &V, bool initial = false) {
++  bool setLocation(Option &O, DataType &L) {
++    Value = L;
++    Default = Value;
++    return false;
++  }
++
++  void setValue(const DataType &V, bool initial = false) {
++    Value = V;
++    if (initial)
++      Default = V;
++  }
++
++  template<typename T>
++  void setValue(const T &V, bool initial = false) {
+     Value = V;
+     if (initial)
+       Default = V;
+   }
++
+   DataType &getValue() { return Value; }
+   DataType getValue() const { return Value; }
+ 
+   const OptionValue<DataType> &getDefault() const { return Default; }
+ 
+-  operator DataType() const { return getValue(); }
++  operator DataType() const { return Value; }
+ 
+   // If the datatype is a pointer, support -> on it.
+   DataType operator->() const { return Value; }
+@@ -1184,19 +2059,57 @@
+ //===----------------------------------------------------------------------===//
+ // opt - A scalar command line option.
+ //
+-template <class DataType, bool ExternalStorage = false,
+-          class ParserClass = parser<DataType>>
+-class opt : public Option,
+-            public opt_storage<DataType, ExternalStorage,
+-                               std::is_class<DataType>::value> {
++template<typename DataType, bool ExternalStorage = false,
++         typename ParserClass = parser<DataType> >
++class LLVM_ALIGNAS(8) opt : public Option,
++                            public opt_storage<DataType, ExternalStorage,
++                            std::is_class<DataType>::value> {
+   ParserClass Parser;
+ 
+-  bool handleOccurrence(unsigned pos, StringRef ArgName,
++public:
++  opt<DataType, ExternalStorage, ParserClass>()
++  : Option(), opt_storage<DataType, ExternalStorage,
++  std::is_class<DataType>::value>(), Parser(*this) { }
++
++  opt<DataType, ExternalStorage, ParserClass>(
++    const opt<DataType, ExternalStorage, ParserClass> &RHS) : Option(RHS),
++  opt_storage<DataType, ExternalStorage,
++  std::is_class<DataType>::value>(RHS), Parser(RHS.Parser) { }
++
++  opt<DataType, ExternalStorage, ParserClass>&
++  operator=(const opt<DataType, ExternalStorage, ParserClass> &RHS) {
++    if (this != &RHS) {
++      Option::operator=(RHS);
++      opt_storage<DataType, ExternalStorage,
++                  std::is_class<DataType>::value>::operator=(RHS);
++      Parser = RHS.Parser;
++    }
++
++    return *this;
++  }
++
++  const opt<DataType, ExternalStorage, ParserClass>&
++  operator=(opt<DataType, ExternalStorage, ParserClass> &&RHS) {
++    if (this != &RHS) {
++      Option::operator=(RHS);
++      opt_storage<DataType, ExternalStorage,
++                  std::is_class<DataType>::value>::operator=(RHS);
++      Parser = std::move(RHS.Parser);
++    }
++
++    return *this;
++  }
++
++  virtual ~opt<DataType, ExternalStorage, ParserClass>() { }
++
++protected:
++  virtual bool handleOccurrence(unsigned pos, StringRef ArgName,
+                         StringRef Arg) override {
+     typename ParserClass::parser_data_type Val =
+         typename ParserClass::parser_data_type();
+     if (Parser.parse(*this, ArgName, Arg, Val))
+       return true; // Parse error!
++
+     this->setValue(Val);
+     this->setPosition(pos);
+     return false;
+@@ -1205,7 +2118,9 @@
+   enum ValueExpected getValueExpectedFlagDefault() const override {
+     return Parser.getValueExpectedFlagDefault();
+   }
+-  void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override {
++
++  virtual void
++  getExtraOptionNames(std::vector<const char*> &OptionNames) override {
+     return Parser.getExtraOptionNames(OptionNames);
+   }
+ 
+@@ -1213,6 +2128,7 @@
+   size_t getOptionWidth() const override {
+     return Parser.getOptionWidth(*this);
+   }
++
+   void printOptionInfo(size_t GlobalWidth) const override {
+     Parser.printOptionInfo(*this, GlobalWidth);
+   }
+@@ -1229,34 +2145,44 @@
+     Parser.initialize();
+   }
+ 
+-  // Command line options should not be copyable
+-  opt(const opt &) = delete;
+-  opt &operator=(const opt &) = delete;
+-
+ public:
+   // setInitialValue - Used by the cl::init modifier...
+   void setInitialValue(const DataType &V) { this->setValue(V, true); }
+ 
++  bool setLocation(Option &O, DataType &L) {
++    bool R = opt_storage<DataType, ExternalStorage,
++         std::is_class<DataType>::value>::setLocation(O, L);
++    return R;
++  }
++
++  void addArgument() {
++    assert(!NextRegistered && "argument multiply registered!");
++    Option::registerOption(this);
++  }
++
+   ParserClass &getParser() { return Parser; }
+ 
+-  template <class T> DataType &operator=(const T &Val) {
++  template<typename T> DataType &operator=(const T &Val) {
+     this->setValue(Val);
+     return this->getValue();
+   }
+ 
+-  template <class... Mods>
++  template <typename... Mods>
+   explicit opt(const Mods &... Ms)
+-      : Option(Optional, NotHidden), Parser(*this) {
++  : Option(Optional, NotHidden),
++  opt_storage<DataType, ExternalStorage, std::is_class<DataType>::value>(),
++  Parser(*this) {
+     apply(this, Ms...);
+     done();
+   }
+ };
+ 
+-extern template class opt<unsigned>;
+-extern template class opt<int>;
+-extern template class opt<std::string>;
+-extern template class opt<char>;
+-extern template class opt<bool>;
++// extern template class opt<unsigned>;
++// extern template class opt<int>;
++// extern template class opt<std::string>;
++// extern template class opt<char>;
++// extern template class opt<bool>;
++// extern template class opt<unsigned long long>;
+ 
+ //===----------------------------------------------------------------------===//
+ // list_storage class
+@@ -1265,22 +2191,72 @@
+ // assumes the user will specify a variable to store the data into with the
+ // cl::location(x) modifier.
+ //
+-template <class DataType, class StorageClass> class list_storage {
++template<typename DataType, typename StorageClass>
++class list_storage {
++private:
+   StorageClass *Location; // Where to store the object...
+ 
+ public:
+-  list_storage() : Location(0) {}
++  list_storage<DataType, StorageClass>() : Location(nullptr) { }
++
++  list_storage<DataType, StorageClass>(
++    const list_storage<DataType, StorageClass> &RHS)
++  : Location(RHS.Location) { }
++
++  list_storage<DataType, StorageClass>(
++    list_storage<DataType, StorageClass> &&RHS)
++  : Location(RHS.Location) { }
++
++  virtual ~list_storage<DataType, StorageClass>() { }
++
++  list_storage<DataType, StorageClass>&
++  operator=(const list_storage<DataType, StorageClass> &RHS) {
++    if (this != &RHS)
++      Location = RHS.Location;
++
++    return *this;
++  }
++
++  const list_storage<DataType, StorageClass>&
++  operator=(list_storage<DataType, StorageClass> &&RHS) {
++    if (this != &RHS)
++      Location = std::move(RHS.Location);
++
++    return *this;
++  }
+ 
+   bool setLocation(Option &O, StorageClass &L) {
+     if (Location)
+       return O.error("cl::location(x) specified more than once!");
++
+     Location = &L;
+     return false;
+   }
+ 
+-  template <class T> void addValue(const T &V) {
++  void addValue(const DataType &V) {
++    assert(Location != 0 && "cl::location(...) not specified for a command "
++                            "line option with external storage!");
++    if (!Location) {
++      llvm::errs() << __PRETTY_FUNCTION__
++        << ": cl::location(...) not specified for a command "
++        << "line option with external storage!\n";
++      abort();
++    }
++
++    Location->push_back(V);
++  }
++
++  template <typename T>
++  void addValue(const T &V) {
+     assert(Location != 0 && "cl::location(...) not specified for a command "
+                             "line option with external storage!");
++    if (!Location) {
++      llvm::errs() << __PRETTY_FUNCTION__
++        << ": cl::location(...) not specified for a command "
++        << "line option with external storage!\n";
++      abort();
++    }
++
+     Location->push_back(V);
+   }
+ };
+@@ -1293,10 +2269,24 @@
+ //
+ // FIXME: Reduce this API to a more narrow subset of std::vector
+ //
+-template <class DataType> class list_storage<DataType, bool> {
++template <typename DataType>
++class list_storage<DataType, bool> {
+   std::vector<DataType> Storage;
+ 
+ public:
++  list_storage<DataType, bool>() : Storage() { }
++  list_storage<DataType, bool>(const list_storage<DataType, bool> &RHS)
++    : Storage(RHS.Storage) { }
++  virtual ~list_storage<DataType, bool>() { }
++
++  list_storage<DataType, bool>
++  &operator=(const list_storage<DataType, bool> &RHS) {
++    if (this != &RHS)
++      Storage = RHS.Storage;
++
++    return *this;
++  }
++
+   typedef typename std::vector<DataType>::iterator iterator;
+ 
+   iterator begin() { return Storage.begin(); }
+@@ -1332,6 +2322,7 @@
+   iterator insert(const_iterator pos, const DataType &value) {
+     return Storage.insert(pos, value);
+   }
++
+   iterator insert(const_iterator pos, DataType &&value) {
+     return Storage.insert(pos, value);
+   }
+@@ -1339,6 +2330,7 @@
+   iterator insert(iterator pos, const DataType &value) {
+     return Storage.insert(pos, value);
+   }
++
+   iterator insert(iterator pos, DataType &&value) {
+     return Storage.insert(pos, value);
+   }
+@@ -1351,48 +2343,68 @@
+   std::vector<DataType> *operator&() { return &Storage; }
+   const std::vector<DataType> *operator&() const { return &Storage; }
+ 
+-  template <class T> void addValue(const T &V) { Storage.push_back(V); }
++  template<typename T>
++  void addValue(const T &V) {
++    T LV(V);
++    Storage.push_back(LV);
++  }
++
++  void addValue(const DataType &V) {
++    DataType LV(V);
++    Storage.push_back(LV);
++  }
++
++  const std::vector<DataType> &getStorage() const {
++    return Storage;
++  }
+ };
+ 
+ //===----------------------------------------------------------------------===//
+ // list - A list of command line options.
+ //
+-template <class DataType, class StorageClass = bool,
+-          class ParserClass = parser<DataType>>
++template<typename DataType, typename StorageClass = bool,
++         typename ParserClass = parser<DataType> >
+ class list : public Option, public list_storage<DataType, StorageClass> {
++  friend class Option;
+   std::vector<unsigned> Positions;
+   ParserClass Parser;
+ 
+-  enum ValueExpected getValueExpectedFlagDefault() const override {
++protected:
++  virtual enum ValueExpected getValueExpectedFlagDefault() const override {
+     return Parser.getValueExpectedFlagDefault();
+   }
+-  void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override {
++
++  virtual void
++  getExtraOptionNames(std::vector<const char*> &OptionNames) override {
+     return Parser.getExtraOptionNames(OptionNames);
+   }
+ 
+-  bool handleOccurrence(unsigned pos, StringRef ArgName,
++  virtual bool handleOccurrence(unsigned pos, StringRef ArgName,
+                         StringRef Arg) override {
+     typename ParserClass::parser_data_type Val =
+         typename ParserClass::parser_data_type();
+     if (Parser.parse(*this, ArgName, Arg, Val))
+       return true; // Parse Error!
+-    list_storage<DataType, StorageClass>::addValue(Val);
++
++    // list_storage<DataType, StorageClass>::addValue(Val);
++    this->addValue(Val);
+     setPosition(pos);
+     Positions.push_back(pos);
+     return false;
+   }
+ 
+   // Forward printing stuff to the parser...
+-  size_t getOptionWidth() const override {
++  virtual size_t getOptionWidth() const override {
+     return Parser.getOptionWidth(*this);
+   }
+-  void printOptionInfo(size_t GlobalWidth) const override {
++
++  virtual void printOptionInfo(size_t GlobalWidth) const override {
+     Parser.printOptionInfo(*this, GlobalWidth);
+   }
+ 
+   // Unimplemented: list options don't currently store their default value.
+-  void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
+-  }
++  virtual void
++  printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override { }
+ 
+   void done() {
+     addArgument();
+@@ -1400,22 +2412,46 @@
+   }
+ 
+   // Command line options should not be copyable
+-  list(const list &) = delete;
+-  list &operator=(const list &) = delete;
++  list<DataType, StorageClass, ParserClass>(
++    const list<DataType, StorageClass, ParserClass>&) = delete;
++  list<DataType, StorageClass, ParserClass>&
++  operator=(const list<DataType, StorageClass, ParserClass>&) = delete;
+ 
+ public:
++  list<DataType, StorageClass, ParserClass>()
++  : Option(), list_storage<DataType, StorageClass>(),
++  Positions(), Parser(ParserClass()) { }
++
++  list<DataType, StorageClass, ParserClass>(const Option &O)
++  : Option(O), list_storage<DataType, StorageClass>(),
++  Positions(), Parser(ParserClass()) { }
++
++  list<DataType, StorageClass, ParserClass>(Option *O)
++  : Option(*O), list_storage<DataType, StorageClass>(),
++  Positions(), Parser(ParserClass()) { }
++
++  ~list<DataType, StorageClass, ParserClass>() { }
++
+   ParserClass &getParser() { return Parser; }
+ 
++  void addArgument() {
++    assert(!NextRegistered && "argument multiply registered!");
++    Option::registerOption(this);
++  }
++
+   unsigned getPosition(unsigned optnum) const {
+     assert(optnum < this->size() && "Invalid option index");
+     return Positions[optnum];
+   }
+ 
+-  void setNumAdditionalVals(unsigned n) { Option::setNumAdditionalVals(n); }
++  void setNumAdditionalVals(unsigned N) {
++    Option::setNumAdditionalVals(N);
++  }
+ 
+-  template <class... Mods>
+-  explicit list(const Mods &... Ms)
+-      : Option(ZeroOrMore, NotHidden), Parser(*this) {
++  template <typename... Mods>
++  explicit list<DataType, StorageClass, ParserClass>(const Mods &... Ms)
++  : Option(ZeroOrMore, NotHidden), list_storage<DataType, StorageClass>(),
++  Positions(), Parser(*this) {
+     apply(this, Ms...);
+     done();
+   }
+@@ -1424,7 +2460,9 @@
+ // multi_val - Modifier to set the number of additional values.
+ struct multi_val {
+   unsigned AdditionalVals;
++  multi_val() : AdditionalVals(0U) { }
+   explicit multi_val(unsigned N) : AdditionalVals(N) {}
++  ~multi_val() { }
+ 
+   template <typename D, typename S, typename P>
+   void apply(list<D, S, P> &L) const {
+@@ -1439,10 +2477,11 @@
+ // assumes the user will specify a variable to store the data into with the
+ // cl::location(x) modifier.
+ //
+-template <class DataType, class StorageClass> class bits_storage {
++template<typename DataType, typename StorageClass>
++class bits_storage {
+   unsigned *Location; // Where to store the bits...
+ 
+-  template <class T> static unsigned Bit(const T &V) {
++  template<typename T> static unsigned Bit(const T &V) {
+     unsigned BitPos = reinterpret_cast<unsigned>(V);
+     assert(BitPos < sizeof(unsigned) * CHAR_BIT &&
+            "enum exceeds width of bit vector!");
+@@ -1475,41 +2514,59 @@
+ // Define how to hold bits.  Since we can inherit from a class, we do so.
+ // This makes us exactly compatible with the bits in all cases that it is used.
+ //
+-template <class DataType> class bits_storage<DataType, bool> {
++template<typename DataType>
++class bits_storage<DataType, bool> {
+   unsigned Bits; // Where to store the bits...
+ 
+-  template <class T> static unsigned Bit(const T &V) {
+-    unsigned BitPos = (unsigned)V;
++  template<typename T> static unsigned Bit(const T &V) {
++    unsigned BitPos = static_cast<unsigned>(V);
+     assert(BitPos < sizeof(unsigned) * CHAR_BIT &&
+            "enum exceeds width of bit vector!");
+     return 1 << BitPos;
+   }
+ 
+ public:
+-  template <class T> void addValue(const T &V) { Bits |= Bit(V); }
++  void addValue(const DataType &V) {
++    Bits |= Bit(V);
++  }
++
++  template<typename T>
++  void addValue(const T &V) {
++    Bits |= Bit(V);
++  }
+ 
+   unsigned getBits() { return Bits; }
+ 
+-  template <class T> bool isSet(const T &V) { return (Bits & Bit(V)) != 0; }
++  bool isSet(const DataType &V) {
++    return (Bits & Bit(V)) != 0;
++  }
++
++  template<typename T>
++  bool isSet(const T &V) {
++    return (Bits & Bit(V)) != 0;
++  }
+ };
+ 
+ //===----------------------------------------------------------------------===//
+ // bits - A bit vector of command options.
+ //
+-template <class DataType, class Storage = bool,
+-          class ParserClass = parser<DataType>>
++template<typename DataType, typename Storage = bool,
++         typename ParserClass = parser<DataType> >
+ class bits : public Option, public bits_storage<DataType, Storage> {
+   std::vector<unsigned> Positions;
+   ParserClass Parser;
+ 
+-  enum ValueExpected getValueExpectedFlagDefault() const override {
++protected:
++  virtual enum ValueExpected getValueExpectedFlagDefault() const override {
+     return Parser.getValueExpectedFlagDefault();
+   }
+-  void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override {
++
++  virtual void
++  getExtraOptionNames(std::vector<const char*> &OptionNames) override {
+     return Parser.getExtraOptionNames(OptionNames);
+   }
+ 
+-  bool handleOccurrence(unsigned pos, StringRef ArgName,
++  virtual bool handleOccurrence(unsigned pos, StringRef ArgName,
+                         StringRef Arg) override {
+     typename ParserClass::parser_data_type Val =
+         typename ParserClass::parser_data_type();
+@@ -1525,6 +2582,7 @@
+   size_t getOptionWidth() const override {
+     return Parser.getOptionWidth(*this);
+   }
++
+   void printOptionInfo(size_t GlobalWidth) const override {
+     Parser.printOptionInfo(*this, GlobalWidth);
+   }
+@@ -1538,11 +2596,20 @@
+     Parser.initialize();
+   }
+ 
++private:
+   // Command line options should not be copyable
+-  bits(const bits &) = delete;
+-  bits &operator=(const bits &) = delete;
++  bits<DataType, Storage, ParserClass>(
++    const bits<DataType, Storage, ParserClass>&) = delete;
++  bits<DataType, Storage, ParserClass>
++  &operator=(const bits<DataType, Storage, ParserClass>&) = delete;
+ 
+ public:
++  bits<DataType, Storage, ParserClass>()
++  : Option(ZeroOrMore, NotHidden), bits_storage<DataType, Storage>(),
++  Positions(), Parser() { }
++
++  ~bits() { }
++
+   ParserClass &getParser() { return Parser; }
+ 
+   unsigned getPosition(unsigned optnum) const {
+@@ -1550,9 +2617,10 @@
+     return Positions[optnum];
+   }
+ 
+-  template <class... Mods>
+-  explicit bits(const Mods &... Ms)
+-      : Option(ZeroOrMore, NotHidden), Parser(*this) {
++  template<typename... Mods>
++  explicit bits<DataType, Storage, ParserClass>(const Mods &... Ms)
++  : Option(ZeroOrMore, NotHidden), bits_storage<DataType, Storage>(),
++  Positions(), Parser(*this) {
+     apply(this, Ms...);
+     done();
+   }
+@@ -1568,19 +2636,21 @@
+                         StringRef Arg) override {
+     return AliasFor->handleOccurrence(pos, AliasFor->ArgStr, Arg);
+   }
+-  bool addOccurrence(unsigned pos, StringRef /*ArgName*/, StringRef Value,
+-                     bool MultiArg = false) override {
++
++  virtual bool addOccurrence(unsigned pos, StringRef /*ArgName*/,
++                             StringRef Value, bool MultiArg = false) override {
+     return AliasFor->addOccurrence(pos, AliasFor->ArgStr, Value, MultiArg);
+   }
++
+   // Handle printing stuff...
+   size_t getOptionWidth() const override;
+   void printOptionInfo(size_t GlobalWidth) const override;
+ 
+   // Aliases do not need to print their values.
+-  void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
+-  }
++  virtual void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/)
++    const override { }
+ 
+-  ValueExpected getValueExpectedFlagDefault() const override {
++  virtual ValueExpected getValueExpectedFlagDefault() const override {
+     return AliasFor->getValueExpectedFlag();
+   }
+ 
+@@ -1597,13 +2667,15 @@
+   alias &operator=(const alias &) = delete;
+ 
+ public:
++  alias() : Option(Optional, Hidden), AliasFor(nullptr) { }
++
+   void setAliasFor(Option &O) {
+     if (AliasFor)
+       error("cl::alias must only have one cl::aliasopt(...) specified!");
+     AliasFor = &O;
+   }
+ 
+-  template <class... Mods>
++  template<typename... Mods>
+   explicit alias(const Mods &... Ms)
+       : Option(Optional, Hidden), AliasFor(nullptr) {
+     apply(this, Ms...);
+@@ -1615,6 +2687,7 @@
+ struct aliasopt {
+   Option &Opt;
+   explicit aliasopt(Option &O) : Opt(O) {}
++
+   void apply(alias &A) const { A.setAliasFor(Opt); }
+ };
+ 
+@@ -1624,6 +2697,7 @@
+ // exit is called.
+ struct extrahelp {
+   const char *morehelp;
++
+   explicit extrahelp(const char *help);
+ };
+ 
+@@ -1688,7 +2762,7 @@
+ /// lines and end of the response file to be marked with a nullptr string.
+ /// \param [out] NewArgv All parsed strings are appended to NewArgv.
+ void TokenizeGNUCommandLine(StringRef Source, StringSaver &Saver,
+-                            SmallVectorImpl<const char *> &NewArgv,
++                            std::vector<const char*> &NewArgv,
+                             bool MarkEOLs = false);
+ 
+ /// \brief Tokenizes a Windows command line which may contain quotes and escaped
+@@ -1703,13 +2777,13 @@
+ /// lines and end of the response file to be marked with a nullptr string.
+ /// \param [out] NewArgv All parsed strings are appended to NewArgv.
+ void TokenizeWindowsCommandLine(StringRef Source, StringSaver &Saver,
+-                                SmallVectorImpl<const char *> &NewArgv,
++                                std::vector<const char*> &NewArgv,
+                                 bool MarkEOLs = false);
+ 
+ /// \brief String tokenization function type.  Should be compatible with either
+ /// Windows or Unix command line tokenizers.
+ typedef void (*TokenizerCallback)(StringRef Source, StringSaver &Saver,
+-                                  SmallVectorImpl<const char *> &NewArgv,
++                                  std::vector<const char*> &NewArgv,
+                                   bool MarkEOLs);
+ 
+ /// \brief Expand response files on a command line recursively using the given
+@@ -1720,16 +2794,6 @@
+ /// remaining arguments only until the next end of line, when in a response
+ /// file.
+ ///
+-/// \param [in] Saver Delegates back to the caller for saving parsed strings.
+-/// \param [in] Tokenizer Tokenization strategy. Typically Unix or Windows.
+-/// \param [in,out] Argv Command line into which to expand response files.
+-/// \param [in] MarkEOLs Mark end of lines and the end of the response file
+-/// with nullptrs in the Argv vector.
+-/// \return true if all @files were expanded successfully or there were none.
+-bool ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
+-                         SmallVectorImpl<const char *> &Argv,
+-                         bool MarkEOLs = false);
+-
+ /// \brief Mark all options not part of this category as cl::ReallyHidden.
+ ///
+ /// \param Category the category of options to keep displaying
+@@ -1748,6 +2812,13 @@
+ /// option category to display in the -help output.
+ void HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories);
+ 
++/// \brief Expand response files on a command line recursively using
++/// the given StringSaver and tokenization strategy.
++///
++bool ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
++                         std::vector<const char *> &Argv,
++                         bool MarkEOLs = false);
++
+ } // End namespace cl
+ 
+ } // End namespace llvm
+###
+--- lib/Support/CommandLine.cpp	2015-12-28 06:46:15.000000000 -0900
++++ lib/Support/CommandLine.cpp	2016-07-06 13:40:52.605682650 -0800
+@@ -34,18 +34,23 @@
+ #include "llvm/Support/Path.h"
+ #include "llvm/Support/StringSaver.h"
+ #include "llvm/Support/raw_ostream.h"
+-#include <cstdlib>
+-#include <map>
+ using namespace llvm;
+ using namespace cl;
+ 
++#include <cstdlib>
++#include <string>
++#include <map>
++
+ #define DEBUG_TYPE "commandline"
+ 
++#include <iostream>
++
+ //===----------------------------------------------------------------------===//
+ // Template instantiations and anchors.
+ //
+ namespace llvm {
+ namespace cl {
++typedef std::map<std::string, Option*> StdStringMap;
+ template class basic_parser<bool>;
+ template class basic_parser<boolOrDefault>;
+ template class basic_parser<int>;
+@@ -82,133 +87,197 @@
+ 
+ //===----------------------------------------------------------------------===//
+ 
++namespace llvm {
++  namespace cl {
++    Option *generic_parser_base::DefaultInvalidOption =
++      reinterpret_cast<Option*>(reinterpret_cast<void*>(
++          static_cast<uintptr_t>(0xdeadbeef)));
++  } // namespace cl
++} // namedspace llvm
++
++//===----------------------------------------------------------------------===//
++
+ namespace {
+ 
+ class CommandLineParser {
+ public:
+   // Globals for name and overview of program.  Program name is not a string to
+   // avoid static ctor/dtor issues.
+-  std::string ProgramName;
+-  const char *ProgramOverview;
++  static std::string ProgramName;
++  static const char *ProgramOverview;
+ 
+   // This collects additional help to be printed.
+-  std::vector<const char *> MoreHelp;
++  static std::vector<const char *> MoreHelp;
+ 
+-  SmallVector<Option *, 4> PositionalOpts;
+-  SmallVector<Option *, 4> SinkOpts;
+-  StringMap<Option *> OptionsMap;
++  std::vector<Option*> PositionalOpts;
++  std::vector<Option*> SinkOpts;
++  llvm::cl::StdStringMap OptionsMap;
++  StringMap<Option*> ReturnOptionsMap;
+ 
+   Option *ConsumeAfterOpt; // The ConsumeAfter option if it exists.
+ 
+   // This collects the different option categories that have been registered.
+   SmallPtrSet<OptionCategory *, 16> RegisteredOptionCategories;
+ 
+-  CommandLineParser() : ProgramOverview(nullptr), ConsumeAfterOpt(nullptr) {}
++  // Check out the positional arguments to collect information about them.
++  unsigned NumPositionalRequired;
+ 
+-  void ParseCommandLineOptions(int argc, const char *const *argv,
+-                               const char *Overview);
++  // Determine whether or not there are an unlimited number of positionals
++  bool HasUnlimitedPositionals;
+ 
+-  void addLiteralOption(Option &Opt, const char *Name) {
+-    if (!Opt.hasArgStr()) {
+-      if (!OptionsMap.insert(std::make_pair(Name, &Opt)).second) {
+-        errs() << ProgramName << ": CommandLine Error: Option '" << Name
+-               << "' registered more than once!\n";
+-        report_fatal_error("inconsistency in registered CommandLine options");
+-      }
+-    }
+-  }
++  CommandLineParser()
++  : PositionalOpts(), SinkOpts(), OptionsMap(), ReturnOptionsMap(),
++  ConsumeAfterOpt(0UL), RegisteredOptionCategories(),
++  NumPositionalRequired(0U), HasUnlimitedPositionals(false) { }
+ 
+-  void addOption(Option *O) {
+-    bool HadErrors = false;
+-    if (O->hasArgStr()) {
+-      // Add argument to the argument map!
+-      if (!OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) {
+-        errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
+-               << "' registered more than once!\n";
+-        HadErrors = true;
+-      }
+-    }
++  ~CommandLineParser() { }
+ 
+-    // Remember information about positional options.
+-    if (O->getFormattingFlag() == cl::Positional)
+-      PositionalOpts.push_back(O);
+-    else if (O->getMiscFlags() & cl::Sink) // Remember sink options
+-      SinkOpts.push_back(O);
+-    else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
+-      if (ConsumeAfterOpt) {
+-        O->error("Cannot specify more than one option with cl::ConsumeAfter!");
+-        HadErrors = true;
+-      }
+-      ConsumeAfterOpt = O;
+-    }
++  static void GetOptionInfo(std::vector<Option *> &PO,
++                            std::vector<Option *> &SO,
++                            llvm::cl::StdStringMap &OM);
++
++  static bool ExpandResponseFile(const char *FName,
++                                 StringSaver &Saver,
++                                 TokenizerCallback Tokenizer,
++                                 std::vector<const char *> &NewArgv,
++                                 bool MarkEOLs = false);
++
++  void __attribute__((noinline))
++  ParseCommandLineOptions(int Argc, const char *const *Argv,
++                          const char *Overview);
++
++  void __attribute__((noinline))
++  addLiteralOption(Option &Opt, const char *Name);
++
++  void __attribute__((noinline)) addOption(Option *O);
++
++  void __attribute__((noinline)) removeOption(Option *O);
++
++  bool __attribute__((noinline)) hasOptions();
++
++  void __attribute__((noinline)) updateArgStr(Option *O, StringRef NewName);
++
++  void __attribute__((noinline)) PrintOptionValues();
+ 
+-    // Fail hard if there were errors. These are strictly unrecoverable and
+-    // indicate serious issues such as conflicting option names or an
+-    // incorrectly
+-    // linked LLVM distribution.
+-    if (HadErrors)
++  void __attribute__((noinline)) registerCategory(OptionCategory *cat);
++
++private:
++  Option *LookupOption(StringRef &Arg, StringRef &Value);
++  void HandleSpecialPrefixOptions(StringRef &ArgName, StringRef &Value);
++};
++
++void __attribute__((noinline))
++CommandLineParser::addLiteralOption(Option &Opt, const char *Name) {
++  if (!Opt.hasArgStr()) {
++    if (!OptionsMap.insert(std::make_pair(Name, &Opt)).second) {
++      errs() << __PRETTY_FUNCTION__ << ": " << ProgramName
++        << ": CommandLine Error: Option '" << Name
++        << "' registered more than once!\n";
+       report_fatal_error("inconsistency in registered CommandLine options");
++    }
+   }
++}
+ 
+-  void removeOption(Option *O) {
+-    SmallVector<StringRef, 16> OptionNames;
+-    O->getExtraOptionNames(OptionNames);
+-    if (O->hasArgStr())
+-      OptionNames.push_back(O->ArgStr);
+-    for (auto Name : OptionNames)
+-      OptionsMap.erase(Name);
++void __attribute__((noinline))
++CommandLineParser::addOption(Option *O) {
++  bool HadErrors = false;
++  if (O->hasArgStr()) {
++    // Add argument to the argument map!
++    if (!OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) {
++      errs() << __PRETTY_FUNCTION__ << ": " << ProgramName
++        << ": CommandLine Error: Option '" << O->ArgStr
++        << "' registered more than once!\n";
++      HadErrors = true;
++    }
++  }
+ 
+-    if (O->getFormattingFlag() == cl::Positional)
+-      for (auto Opt = PositionalOpts.begin(); Opt != PositionalOpts.end();
+-           ++Opt) {
+-        if (*Opt == O) {
+-          PositionalOpts.erase(Opt);
+-          break;
+-        }
++  // Remember information about positional options.
++  if (O->getFormattingFlag() == cl::Positional)
++    PositionalOpts.push_back(O);
++  else if (O->getMiscFlags() & cl::Sink) // Remember sink options
++    SinkOpts.push_back(O);
++  else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
++    if (ConsumeAfterOpt) {
++      O->error("Cannot specify more than one option with cl::ConsumeAfter!");
++      HadErrors = true;
++    }
++
++    ConsumeAfterOpt = O;
++  }
++
++  // Fail hard if there were errors. These are strictly unrecoverable and
++  // indicate serious issues such as conflicting option names or an
++  //incorrectly linked LLVM distribution.
++  if (HadErrors)
++    report_fatal_error("inconsistency in registered CommandLine options");
++}
++
++void __attribute__((noinline))
++CommandLineParser::removeOption(Option *O) {
++  std::vector<const char*> OptionNames;
++  O->getExtraOptionNames(OptionNames);
++  if (O->hasArgStr())
++    OptionNames.push_back(O->ArgStr);
++  for (auto Name : OptionNames)
++    OptionsMap.erase(Name);
++
++  if (O->getFormattingFlag() == cl::Positional) {
++    for (auto Opt = PositionalOpts.begin(); Opt != PositionalOpts.end();
++         ++Opt) {
++      if (*Opt == O) {
++        PositionalOpts.erase(Opt);
++        break;
+       }
+-    else if (O->getMiscFlags() & cl::Sink)
+-      for (auto Opt = SinkOpts.begin(); Opt != SinkOpts.end(); ++Opt) {
+-        if (*Opt == O) {
+-          SinkOpts.erase(Opt);
+-          break;
+-        }
++    }
++  } else if (O->getMiscFlags() & cl::Sink) {
++    for (auto Opt = SinkOpts.begin(); Opt != SinkOpts.end(); ++Opt) {
++      if (*Opt == O) {
++        SinkOpts.erase(Opt);
++        break;
+       }
+-    else if (O == ConsumeAfterOpt)
+-      ConsumeAfterOpt = nullptr;
++    }
++  } else if (O == ConsumeAfterOpt) {
++    ConsumeAfterOpt = nullptr;
+   }
++}
+ 
+-  bool hasOptions() {
+-    return (!OptionsMap.empty() || !PositionalOpts.empty() ||
+-            nullptr != ConsumeAfterOpt);
+-  }
++bool __attribute__((noinline))
++CommandLineParser::hasOptions() {
++  return (!OptionsMap.empty() || !PositionalOpts.empty() ||
++          nullptr != ConsumeAfterOpt);
++}
+ 
+-  void updateArgStr(Option *O, StringRef NewName) {
+-    if (!OptionsMap.insert(std::make_pair(NewName, O)).second) {
+-      errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
+-             << "' registered more than once!\n";
+-      report_fatal_error("inconsistency in registered CommandLine options");
+-    }
+-    OptionsMap.erase(O->ArgStr);
++void __attribute__((noinline))
++CommandLineParser::updateArgStr(Option *O, StringRef NewName) {
++  if (!OptionsMap.insert(std::make_pair(NewName, O)).second) {
++    errs() << __PRETTY_FUNCTION__ << ": " << ProgramName
++      << ": CommandLine Error: Option '" << O->ArgStr
++      << "' registered more than once!\n";
++    report_fatal_error("inconsistency in registered CommandLine options");
+   }
+ 
+-  void printOptionValues();
++  OptionsMap.erase(O->ArgStr);
++}
+ 
+-  void registerCategory(OptionCategory *cat) {
+-    assert(std::count_if(RegisteredOptionCategories.begin(),
+-                         RegisteredOptionCategories.end(),
+-                         [cat](const OptionCategory *Category) {
+-                           return cat->getName() == Category->getName();
+-                         }) == 0 &&
+-           "Duplicate option categories");
++void __attribute__((noinline))
++CommandLineParser::registerCategory(OptionCategory *Cat) {
++  assert(std::count_if(RegisteredOptionCategories.begin(),
++                       RegisteredOptionCategories.end(),
++                       [Cat](const OptionCategory *Category) {
++                       return Cat->getName() == Category->getName();
++                       }) == 0 && "Duplicate option categories");
+ 
+-    RegisteredOptionCategories.insert(cat);
+-  }
++  RegisteredOptionCategories.insert(Cat);
++}
+ 
+-private:
+-  Option *LookupOption(StringRef &Arg, StringRef &Value);
+-};
++std::string CommandLineParser::ProgramName("<premain>");
++const char* CommandLineParser::ProgramOverview = 0L;
++std::vector<const char *> CommandLineParser::MoreHelp;
++
++} // end anonymous namespace
+ 
+-} // namespace
++llvm::cl::Option* llvm::cl::Option::RegisteredOptionList = nullptr;
++unsigned llvm::cl::Option::NumRegisteredOptions = 0U;
+ 
+ static ManagedStatic<CommandLineParser> GlobalParser;
+ 
+@@ -222,14 +291,18 @@
+ 
+ void Option::addArgument() {
+   GlobalParser->addOption(this);
++  Option *O = dynamic_cast<Option*>(this);
++  assert(O && "Cannot dynamic_cast to correct type!");
++  Option::registerOption(O);
++
+   FullyInitialized = true;
+ }
+ 
+ void Option::removeArgument() { GlobalParser->removeOption(this); }
+ 
+-void Option::setArgStr(StringRef S) {
++void Option::setArgStr(const char *S) {
+   if (FullyInitialized)
+-    GlobalParser->updateArgStr(this, S);
++    GlobalParser->updateArgStr(this, StringRef(S));
+   ArgStr = S;
+ }
+ 
+@@ -244,6 +317,107 @@
+ // Basic, shared command line option processing machinery.
+ //
+ 
++/// HandleSpecialPrefixOptions - certain options need special handling
++/// of their Argyment/Value pair, because there will be no space separator
++/// between the two. For example -O<N> (optimization level).
++void CommandLineParser::HandleSpecialPrefixOptions(StringRef &ArgName,
++                                                   StringRef &Value) {
++  if (ArgName.empty())
++    return;
++
++  const char *ArgStr = ArgName.data();
++  bool DoSubstitution;
++
++  if (ArgStr[0] == 'O' && ArgStr[1] == '\0')
++    DoSubstitution = true;
++  else if (ArgStr[0] == 'O' && std::isalpha(ArgStr[1]) && ArgStr[2] == '\0')
++    DoSubstitution = true;
++  else if (ArgStr[0] == 'O' && std::isdigit(ArgStr[1]) && ArgStr[2] == '\0')
++    DoSubstitution = true;
++  else if (ArgStr[0] == 'g' && ArgStr[1] == '\0')
++    DoSubstitution = true;
++  else if (ArgStr[0] == 'g' && std::isdigit(ArgStr[1]) && ArgStr[2] == '\0')
++    DoSubstitution = true;
++  else
++    DoSubstitution = false;
++
++  if (DoSubstitution) {
++    Value = ArgName.substr(1, 1);
++    ArgName = ArgName.substr(0, 1);
++  }
++}
++
++/// GetOptionInfo - Scan the list of registered options, turning them into data
++/// structures that are easier to handle.
++void CommandLineParser::GetOptionInfo(std::vector<Option *> &PO,
++                                      std::vector<Option *> &SO,
++                                      llvm::cl::StdStringMap &OM) {
++  bool HadErrors = false;
++  std::vector<const char *> OptionNames;
++  Option *CAOpt = nullptr; // The ConsumeAfter option if it exists.
++
++  for (Option *O = Option::getRegisteredOptionList(); O;
++       O = O->getNextRegisteredOption()) {
++    // If this option wants to handle multiple option names, get the full set.
++    // This handles enum options like "-O1 -O2" etc.
++    O->getExtraOptionNames(OptionNames);
++
++    if (O->ArgStr && *O->ArgStr)
++      OptionNames.push_back(O->ArgStr);
++
++    llvm::cl::StdStringMap::iterator FI;
++
++    // Handle named options.
++    for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
++      // Add argument to the argument map!
++      FI = OM.find(OptionNames[i]);
++      if (FI == OM.end()) {
++        if (!OM.insert(std::make_pair(OptionNames[i], O)).second) {
++          errs() << __PRETTY_FUNCTION__ << ": " << ProgramName.c_str()
++            << ": CommandLine Error: Option '" << OptionNames[i]
++            << "' insertion failed!\n";
++          HadErrors = true;
++        }
++      } else {
++        if (FI->second != O) {
++          errs() << __PRETTY_FUNCTION__ << ": " << ProgramName.c_str()
++            << ": CommandLine Error: Option '"
++            << OptionNames[i] << "' registered more than once!\n";
++          HadErrors = true;
++        }
++      }
++    }
++
++    OptionNames.clear();
++
++    // Remember information about positional options.
++    if (O->getFormattingFlag() == cl::Positional)
++      PO.push_back(O);
++    else if (O->getMiscFlags() & cl::Sink) // Remember sink options
++      SO.push_back(O);
++    else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
++      if (CAOpt) {
++        O->error("Cannot specify more than one option with cl::ConsumeAfter!");
++        HadErrors = true;
++      }
++
++      CAOpt = O;
++    }
++  }
++
++  if (CAOpt)
++    PO.push_back(CAOpt);
++
++  // Make sure that they are in order of registration not backwards.
++  std::reverse(PO.begin(), PO.end());
++
++  // Fail hard if there were errors. These are strictly unrecoverable and
++  // indicate serious issues such as conflicting option names or an incorrectly
++  // linked LLVM distribution.
++  if (HadErrors)
++    report_fatal_error("inconsistency in registered CommandLine options");
++}
++
+ /// LookupOption - Lookup the option specified by the specified option on the
+ /// command line.  If there is a value specified (after an equal sign) return
+ /// that as well.  This assumes that leading dashes have already been stripped.
+@@ -252,18 +426,89 @@
+   if (Arg.empty())
+     return nullptr;
+ 
++  HandleSpecialPrefixOptions(Arg, Value);
++
+   size_t EqualPos = Arg.find('=');
+ 
+   // If we have an equals sign, remember the value.
+   if (EqualPos == StringRef::npos) {
++    StringRef LookupString;
++
+     // Look up the option.
+-    StringMap<Option *>::const_iterator I = OptionsMap.find(Arg);
++    llvm::cl::StdStringMap::const_iterator I = OptionsMap.find(Arg);
++
++    // TableGen
++    if (I == OptionsMap.end()) {
++      LookupString = "<input file>";
++      I = OptionsMap.find(LookupString);
++      if (I != OptionsMap.end())
++        return I->second;
++    }
++
++    // lli && llc
++    if (I == OptionsMap.end()) {
++      LookupString = "<input bitcode>";
++      I = OptionsMap.find(LookupString);
++      if (I != OptionsMap.end())
++        return I->second;
++    }
++
++    // opt
++    if (I == OptionsMap.end()) {
++      LookupString = "<input bitcode file>";
++      I = OptionsMap.find(LookupString);
++      if (I != OptionsMap.end())
++        return I->second;
++    }
++
++    if (I == OptionsMap.end()) {
++      LookupString = "Output filename";
++      I = OptionsMap.find(LookupString);
++      if (I != OptionsMap.end())
++        return I->second;
++    }
++
++    if (I == OptionsMap.end()) {
++      LookupString = "Output Filename";
++      I = OptionsMap.find(LookupString);
++      if (I != OptionsMap.end())
++        return I->second;
++    }
++
++    if (I == OptionsMap.end()) {
++      LookupString = "<Output filename>";
++      I = OptionsMap.find(LookupString);
++      if (I != OptionsMap.end())
++        return I->second;
++    }
++
++    if (I == OptionsMap.end()) {
++      LookupString = "<Output Filename>";
++      I = OptionsMap.find(LookupString);
++      if (I != OptionsMap.end())
++        return I->second;
++    }
++
++    if (I == OptionsMap.end()) {
++      LookupString = "output filename";
++      I = OptionsMap.find(LookupString);
++      if (I != OptionsMap.end())
++        return I->second;
++    }
++
++    if (I == OptionsMap.end()) {
++      LookupString = "<output filename>";
++      I = OptionsMap.find(LookupString);
++      if (I != OptionsMap.end())
++        return I->second;
++    }
++
+     return I != OptionsMap.end() ? I->second : nullptr;
+   }
+ 
+   // If the argument before the = is a valid option name, we match.  If not,
+   // return Arg unmolested.
+-  StringMap<Option *>::const_iterator I =
++  llvm::cl::StdStringMap::const_iterator I =
+       OptionsMap.find(Arg.substr(0, EqualPos));
+   if (I == OptionsMap.end())
+     return nullptr;
+@@ -278,7 +523,7 @@
+ /// (after an equal sign) return that as well.  This assumes that leading dashes
+ /// have already been stripped.
+ static Option *LookupNearestOption(StringRef Arg,
+-                                   const StringMap<Option *> &OptionsMap,
++                                   const llvm::cl::StdStringMap &OptionsMap,
+                                    std::string &NearestString) {
+   // Reject all dashes.
+   if (Arg.empty())
+@@ -292,11 +537,10 @@
+   // Find the closest match.
+   Option *Best = nullptr;
+   unsigned BestDistance = 0;
+-  for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
+-                                           ie = OptionsMap.end();
+-       it != ie; ++it) {
++  for (llvm::cl::StdStringMap::const_iterator it = OptionsMap.begin(),
++       ie = OptionsMap.end(); it != ie; ++it) {
+     Option *O = it->second;
+-    SmallVector<StringRef, 16> OptionNames;
++    std::vector<const char*> OptionNames;
+     O->getExtraOptionNames(OptionNames);
+     if (O->hasArgStr())
+       OptionNames.push_back(O->ArgStr);
+@@ -351,21 +595,33 @@
+ /// ProvideOption - For Value, this differentiates between an empty value ("")
+ /// and a null value (StringRef()).  The later is accepted for arguments that
+ /// don't allow a value (-foo) the former is rejected (-foo=).
+-static inline bool ProvideOption(Option *Handler, StringRef ArgName,
+-                                 StringRef Value, int argc,
+-                                 const char *const *argv, int &i) {
++static bool ProvideOption(Option *Handler, StringRef &ArgName,
++                          StringRef &Value, int Argc,
++                          const char *const *Argv, int &i) {
+   // Is this a multi-argument option?
+   unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
+ 
++  std::string AS = ArgName.str();
++  std::string VS = Value.str();
++
++  if (AS.find("version") != std::string::npos)
++    Value = "true";
++  else if (VS.find("help") != std::string::npos)
++    Value = "true";
++
++  VS = Value.str();
++
+   // Enforce value requirements
+   switch (Handler->getValueExpectedFlag()) {
+   case ValueRequired:
+-    if (!Value.data()) { // No value specified?
+-      if (i + 1 >= argc)
+-        return Handler->error("requires a value!");
++    if (Value.empty()) { // No value specified?
++      if ((i + 1) >= Argc)
++        return Handler->error("argument requires a value!");
++
+       // Steal the next argument, like for '-o filename'
+-      assert(argv && "null check");
+-      Value = argv[++i];
++      assert(Argv && "null check");
++
++      Value = Argv[++i];
+     }
+     break;
+   case ValueDisallowed:
+@@ -373,12 +629,18 @@
+       return Handler->error("multi-valued option specified"
+                             " with ValueDisallowed modifier!");
+ 
+-    if (Value.data())
++    if (!Value.empty())
+       return Handler->error("does not allow a value! '" + Twine(Value) +
+                             "' specified.");
+     break;
+   case ValueOptional:
+     break;
++  case ValuePositionalNoArgs:
++  case ValuePositionalWithArgs:
++    break;
++  default:
++    return Handler->error("Unknown/invalid Option type!");
++    break;
+   }
+ 
+   // If this isn't a multi-arg option, just run the handler.
+@@ -388,30 +650,43 @@
+   // If it is, run the handle several times.
+   bool MultiArg = false;
+ 
+-  if (Value.data()) {
++  if (!Value.empty()) {
+     if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
+       return true;
++
+     --NumAdditionalVals;
+     MultiArg = true;
+   }
+ 
+   while (NumAdditionalVals > 0) {
+-    if (i + 1 >= argc)
++    if ((i + 1) >= Argc)
+       return Handler->error("not enough values!");
+-    assert(argv && "null check");
+-    Value = argv[++i];
++
++    assert(Argv && "null check");
++    Value = Argv[++i];
+ 
+     if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
+       return true;
++
+     MultiArg = true;
+     --NumAdditionalVals;
+   }
++
+   return false;
+ }
+ 
+ static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
+   int Dummy = i;
+-  return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
++  StringRef ArgStr = Handler->ArgStr;
++  bool R = ProvideOption(Handler, ArgStr, Arg, 0, nullptr, Dummy);
++  return R;
++}
++
++static bool ProvidePositionalOptionWithArgs(Option *Handler, StringRef Arg,
++                                            int i, unsigned &ValNo,
++                                            unsigned &NumPositionsRequired) {
++  // FIXME: IMPLEMENT
++  return false;
+ }
+ 
+ // Option predicates...
+@@ -430,9 +705,9 @@
+ //
+ static Option *getOptionPred(StringRef Name, size_t &Length,
+                              bool (*Pred)(const Option *),
+-                             const StringMap<Option *> &OptionsMap) {
++                             const llvm::cl::StdStringMap &OptionsMap) {
+ 
+-  StringMap<Option *>::const_iterator OMI = OptionsMap.find(Name);
++  llvm::cl::StdStringMap::const_iterator OMI = OptionsMap.find(Name);
+ 
+   // Loop while we haven't found an option and Name still has at least two
+   // characters in it (so that the next iteration will not be the empty
+@@ -454,9 +729,9 @@
+ /// see if this is a prefix or grouped option.  If so, split arg into output an
+ /// Arg/Value pair and return the Option to parse it with.
+ static Option *
+-HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
++HandlePrefixedOrGroupedOption(std::string &Arg, std::string &Value,
+                               bool &ErrorParsing,
+-                              const StringMap<Option *> &OptionsMap) {
++                              const llvm::cl::StdStringMap &OptionsMap) {
+   if (Arg.size() == 1)
+     return nullptr;
+ 
+@@ -489,9 +764,10 @@
+     // we don't need to pass argc/argv in.
+     assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
+            "Option can not be cl::Grouping AND cl::ValueRequired!");
++
+     int Dummy = 0;
+-    ErrorParsing |=
+-        ProvideOption(PGOpt, OneArgName, StringRef(), 0, nullptr, Dummy);
++    StringRef ES = "";
++    ErrorParsing |= ProvideOption(PGOpt, OneArgName, ES, 0, nullptr, Dummy);
+ 
+     // Get the next grouping option.
+     PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
+@@ -507,8 +783,12 @@
+ }
+ 
+ static bool EatsUnboundedNumberOfValues(const Option *O) {
+-  return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
+-         O->getNumOccurrencesFlag() == cl::OneOrMore;
++  return O->getNumOccurrencesFlag() == cl::Required ||
++    O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
++    O->getNumOccurrencesFlag() == cl::OneOrMore ||
++    O->getValueExpectedFlag() == cl::ValueRequired ||
++    O->getValueExpectedFlag() == cl::ValuePositionalNoArgs ||
++    O->getValueExpectedFlag() == cl::ValuePositionalWithArgs;
+ }
+ 
+ static bool isWhitespace(char C) { return strchr(" \t\n\r\f\v", C); }
+@@ -518,7 +798,7 @@
+ static bool isGNUSpecial(char C) { return strchr("\\\"\' ", C); }
+ 
+ void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
+-                                SmallVectorImpl<const char *> &NewArgv,
++                                std::vector<const char*> &NewArgv,
+                                 bool MarkEOLs) {
+   SmallString<128> Token;
+   for (size_t I = 0, E = Src.size(); I != E; ++I) {
+@@ -594,7 +874,8 @@
+ ///    consumed in this case.
+ ///
+ ///  * Otherwise, backslashes are interpreted literally.
+-static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
++static size_t parseBackslash(StringRef Src, size_t I,
++                             SmallString<512> &Token) {
+   size_t E = Src.size();
+   int BackslashCount = 0;
+   // Skip the backslashes.
+@@ -616,9 +897,9 @@
+ }
+ 
+ void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
+-                                    SmallVectorImpl<const char *> &NewArgv,
++                                    std::vector<const char*> &NewArgv,
+                                     bool MarkEOLs) {
+-  SmallString<128> Token;
++  SmallString<512> Token;
+ 
+   // This is a small state machine to consume characters until it reaches the
+   // end of the source string.
+@@ -699,14 +980,16 @@
+   return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
+ }
+ 
+-static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
++bool CommandLineParser::ExpandResponseFile(const char *FName,
++                                           StringSaver &Saver,
+                                TokenizerCallback Tokenizer,
+-                               SmallVectorImpl<const char *> &NewArgv,
+-                               bool MarkEOLs = false) {
++                                           std::vector<const char *> &NewArgv,
++                                           bool MarkEOLs) {
+   ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
+       MemoryBuffer::getFile(FName);
+   if (!MemBufOrErr)
+     return false;
++
+   MemoryBuffer &MemBuf = *MemBufOrErr.get();
+   StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
+ 
+@@ -730,10 +1013,13 @@
+   return true;
+ }
+ 
+-/// \brief Expand response files on a command line recursively using the given
+-/// StringSaver and tokenization strategy.
+-bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
+-                             SmallVectorImpl<const char *> &Argv,
++namespace llvm {
++  namespace cl {
++    /// \brief Expand response files on a command line recursively using
++    /// the given StringSaver and tokenization strategy.
++    bool ExpandResponseFiles(StringSaver &Saver,
++                             TokenizerCallback Tokenizer,
++                             std::vector<const char *> &Argv,
+                              bool MarkEOLs) {
+   unsigned RspFiles = 0;
+   bool AllExpanded = true;
+@@ -741,37 +1027,43 @@
+   // Don't cache Argv.size() because it can change.
+   for (unsigned I = 0; I != Argv.size();) {
+     const char *Arg = Argv[I];
++
+     // Check if it is an EOL marker
+     if (Arg == nullptr) {
+       ++I;
+       continue;
+     }
++
+     if (Arg[0] != '@') {
+       ++I;
+       continue;
+     }
+ 
+-    // If we have too many response files, leave some unexpanded.  This avoids
+-    // crashing on self-referential response files.
++        // If we have too many response files, leave some unexpanded.
++        // This avoids crashing on self-referential response files.
+     if (RspFiles++ > 20)
+       return false;
+ 
+     // Replace this response file argument with the tokenization of its
+-    // contents.  Nested response files are expanded in subsequent iterations.
+-    // FIXME: If a nested response file uses a relative path, is it relative to
+-    // the cwd of the process or the response file?
+-    SmallVector<const char *, 0> ExpandedArgv;
+-    if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv,
+-                            MarkEOLs)) {
+-      // We couldn't read this file, so we leave it in the argument stream and
+-      // move on.
++        // contents.  Nested response files are expanded in subsequent
++        // iterations.
++        // FIXME: If a nested response file uses a relative path, is it
++        // relative to the cwd of the process or the response file?
++        std::vector<const char*> ExpandedArgv;
++        if (!CommandLineParser::ExpandResponseFile(Arg + 1, Saver, Tokenizer,
++                                                   ExpandedArgv, MarkEOLs)) {
++          // We couldn't read this file, so we leave it in the argument stream
++          // and move on.
+       AllExpanded = false;
+       ++I;
+       continue;
+     }
++
+     Argv.erase(Argv.begin() + I);
+-    Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
++        Argv.insert(Argv.begin() + I, ExpandedArgv.begin(),
++                    ExpandedArgv.end());
+   }
++
+   return AllExpanded;
+ }
+ 
+@@ -780,7 +1072,7 @@
+ /// from the caller (as PROGNAME) and its command-line arguments from
+ /// an environment variable (whose name is given in ENVVAR).
+ ///
+-void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
++    void ParseEnvironmentOptions(const char *progName, const char *envVar,
+                                  const char *Overview) {
+   // Check args.
+   assert(progName && "Program name not specified");
+@@ -793,53 +1085,65 @@
+ 
+   // Get program's "name", which we wouldn't know without the caller
+   // telling us.
+-  SmallVector<const char *, 20> newArgv;
++      std::vector<const char*> NewArgv;
+   BumpPtrAllocator A;
+   StringSaver Saver(A);
+-  newArgv.push_back(Saver.save(progName));
++      NewArgv.push_back(Saver.save(progName));
+ 
+   // Parse the value of the environment variable into a "command line"
+   // and hand it off to ParseCommandLineOptions().
+-  TokenizeGNUCommandLine(envValue, Saver, newArgv);
+-  int newArgc = static_cast<int>(newArgv.size());
+-  ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
++      TokenizeGNUCommandLine(envValue, Saver, NewArgv);
++      int NewArgc = static_cast<int>(NewArgv.size());
++      ParseCommandLineOptions(NewArgc, &NewArgv[0], Overview);
+ }
+ 
+-void cl::ParseCommandLineOptions(int argc, const char *const *argv,
++    void ParseCommandLineOptions(int Argc, const char *const *Argv,
+                                  const char *Overview) {
+-  GlobalParser->ParseCommandLineOptions(argc, argv, Overview);
++      GlobalParser->ParseCommandLineOptions(Argc, Argv, Overview);
+ }
++  } // end namespace cl
++} // end namespace llvm
+ 
+-void CommandLineParser::ParseCommandLineOptions(int argc,
+-                                                const char *const *argv,
+-                                                const char *Overview) {
+-  assert(hasOptions() && "No options specified!");
+-
++void __attribute__((noinline))
++CommandLineParser::ParseCommandLineOptions(int Argc,
++                                           const char *const *Argv,
++                                           const char *Overview) {
+   // Expand response files.
+-  SmallVector<const char *, 20> newArgv(argv, argv + argc);
++  std::vector<const char*> NewArgv;
++  for (int i = 0; i != Argc; ++i)
++    NewArgv.push_back(Argv[i]);
++
++  // You have no clue what's wrong with this, do you. Time for some
++  // cargo-cult programming. Make up a new and useless class, throw
++  // in a new allocator for no valid reason and hope for the best,
++  // without inasmuch as an inkling as to what is wrong with all of
++  // this code to begin with.
+   BumpPtrAllocator A;
+   StringSaver Saver(A);
+-  ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
+-  argv = &newArgv[0];
+-  argc = static_cast<int>(newArgv.size());
++  llvm::cl::ExpandResponseFiles(Saver, TokenizeGNUCommandLine, NewArgv);
++  Argv = &NewArgv[0];
++  Argc = static_cast<int>(NewArgv.size());
+ 
+   // Copy the program name into ProgName, making sure not to overflow it.
+-  ProgramName = sys::path::filename(argv[0]);
++  CommandLineParser::ProgramName = sys::path::filename(Argv[0]);
+ 
+   ProgramOverview = Overview;
+   bool ErrorParsing = false;
+ 
+-  // Check out the positional arguments to collect information about them.
+-  unsigned NumPositionalRequired = 0;
+-
+-  // Determine whether or not there are an unlimited number of positionals
+-  bool HasUnlimitedPositionals = false;
++  CommandLineParser::GetOptionInfo(PositionalOpts, SinkOpts, OptionsMap);
++  assert(hasOptions() && "No options specified!");
+ 
+   if (ConsumeAfterOpt) {
+     assert(PositionalOpts.size() > 0 &&
+            "Cannot specify cl::ConsumeAfter without a positional argument!");
+   }
++
+   if (!PositionalOpts.empty()) {
++    if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
++      assert(PositionalOpts.size() > 1 &&
++             "Cannot specify cl::ConsumeAfter without a positional argument!");
++      ConsumeAfterOpt = PositionalOpts[0];
++    }
+ 
+     // Calculate how many positional values are _required_.
+     bool UnboundedFound = false;
+@@ -850,12 +1154,12 @@
+       else if (ConsumeAfterOpt) {
+         // ConsumeAfter cannot be combined with "optional" positional options
+         // unless there is only one positional argument...
+-        if (PositionalOpts.size() > 1)
++        if (PositionalOpts.size() > 2)
+           ErrorParsing |= Opt->error(
+               "error - this positional option will never be matched, "
+               "because it does not Require a value, and a "
+               "cl::ConsumeAfter option is active!");
+-      } else if (UnboundedFound && !Opt->hasArgStr()) {
++      } else if (UnboundedFound && !Opt->ArgStr[0]) {
+         // This option does not "require" a value...  Make sure this option is
+         // not specified after an option that eats all extra arguments, or this
+         // one will never get any!
+@@ -864,19 +1168,21 @@
+                                    "another positional argument will match an "
+                                    "unbounded number of values, and this option"
+                                    " does not require a value!");
+-        errs() << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr
+-               << "' is all messed up!\n";
++        errs() << ProgramName << ": CommandLine Error: Option '"
++          << Opt->ArgStr << "' is all messed up!\n";
+         errs() << PositionalOpts.size();
+       }
++
+       UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
+     }
++
+     HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
+   }
+ 
+   // PositionalVals - A vector of "positional" arguments we accumulate into
+   // the process at the end.
+   //
+-  SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
++  std::vector<std::pair<StringRef, unsigned> > PositionalVals;
+ 
+   // If the program has named positional arguments, and the name has been run
+   // across, keep track of which positional argument was named.  Otherwise put
+@@ -885,40 +1191,51 @@
+ 
+   // Loop over all of the arguments... processing them.
+   bool DashDashFound = false; // Have we read '--'?
+-  for (int i = 1; i < argc; ++i) {
++  for (int i = 1; i < Argc; ++i) {
+     Option *Handler = nullptr;
+     Option *NearestHandler = nullptr;
+     std::string NearestHandlerString;
+-    StringRef Value;
++    StringRef Value = "";
+     StringRef ArgName = "";
+ 
+     // Check to see if this is a positional argument.  This argument is
+     // considered to be positional if it doesn't start with '-', if it is "-"
+     // itself, or if we have seen "--" already.
+     //
+-    if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
++    if (((Argv[i][0] != '-') && (Argv[i][1] != '\0')) ||
++        ((Argv[i][0] == '-') && (Argv[i][1] == '\0')) || DashDashFound) {
+       // Positional argument!
+       if (ActivePositionalArg) {
+-        ProvidePositionalOption(ActivePositionalArg, argv[i], i);
++        ProvidePositionalOption(ActivePositionalArg, Argv[i], i);
++        continue; // We are done!
++      }
++
++      ArgName = Argv[i - 1];
++      Value = Argv[i];
++      Handler = LookupOption(ArgName, Value);
++      if (Handler && (Handler->getValueExpectedFlag() == cl::ValueRequired ||
++                      Handler->getValueExpectedFlag() == cl::ValueOptional)) {
++        ErrorParsing |= ProvideOption(Handler, ArgName, Value,
++                                      Argc, Argv, i);
+         continue; // We are done!
+       }
+ 
+       if (!PositionalOpts.empty()) {
+-        PositionalVals.push_back(std::make_pair(argv[i], i));
++        PositionalVals.push_back(std::make_pair(Argv[i], i));
+ 
+         // All of the positional arguments have been fulfulled, give the rest to
+         // the consume after option... if it's specified...
+         //
+         if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
+-          for (++i; i < argc; ++i)
+-            PositionalVals.push_back(std::make_pair(argv[i], i));
++          for (++i; i < Argc; ++i)
++            PositionalVals.push_back(std::make_pair(Argv[i], i));
+           break; // Handle outside of the argument processing loop...
+         }
+ 
+         // Delay processing positional arguments until the end...
+         continue;
+       }
+-    } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
++    } else if (Argv[i][0] == '-' && Argv[i][1] == '-' && Argv[i][2] == 0 &&
+                !DashDashFound) {
+       DashDashFound = true; // This is the mythical "--"?
+       continue;             // Don't try to process it as an argument itself.
+@@ -927,29 +1244,65 @@
+       // If there is a positional argument eating options, check to see if this
+       // option is another positional argument.  If so, treat it as an argument,
+       // otherwise feed it to the eating positional.
+-      ArgName = argv[i] + 1;
++      ArgName = Argv[i] + 1;
++
+       // Eat leading dashes.
+       while (!ArgName.empty() && ArgName[0] == '-')
+         ArgName = ArgName.substr(1);
+ 
+       Handler = LookupOption(ArgName, Value);
++      if (Handler && (Handler->getValueExpectedFlag() == cl::ValueRequired ||
++                      Handler->getValueExpectedFlag() == cl::ValueOptional)) {
++        ErrorParsing |= ProvideOption(Handler, ArgName, Value,
++                                      Argc, Argv, i);
++        continue; // We are done!
++      }
++
+       if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
+-        ProvidePositionalOption(ActivePositionalArg, argv[i], i);
++        ProvidePositionalOption(ActivePositionalArg, Argv[i], i);
+         continue; // We are done!
+       }
+ 
+     } else { // We start with a '-', must be an argument.
+-      ArgName = argv[i] + 1;
++      ArgName = Argv[i];
++
+       // Eat leading dashes.
+       while (!ArgName.empty() && ArgName[0] == '-')
+         ArgName = ArgName.substr(1);
+ 
+       Handler = LookupOption(ArgName, Value);
++      if (Handler) {
++        enum FormattingFlags FF = Handler->getFormattingFlag();
++        enum ValueExpected VEF = Handler->getValueExpectedFlag();
++
++        if ((FF == llvm::cl::Prefix) || (FF == llvm::cl::Grouping)) {
++          if (Value.empty())
++            Value = Argv[++i];
++
++          std::string SA = ArgName.str();
++          std::string SV = Value.str();
++          SA.append(SV);
++
++          // Check to see if this "option" is really a prefixed or
++          // grouped argument.
++          Option *PrefixOrGroupHandler =
++            HandlePrefixedOrGroupedOption(SA, SV, ErrorParsing, OptionsMap);
++          if (PrefixOrGroupHandler)
++            Handler = PrefixOrGroupHandler;
++        } else if (VEF == llvm::cl::ValueRequired) {
++          ErrorParsing |= ProvideOption(Handler, ArgName, Value, Argc,
++                                        Argv, i);
++          continue; // We are done!
++        }
++      }
+ 
+       // Check to see if this "option" is really a prefixed or grouped argument.
+-      if (!Handler)
+-        Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
++      if (!Handler) {
++        std::string SA = ArgName.str();
++        std::string SV = Value.str();
++        Handler = HandlePrefixedOrGroupedOption(SA, SV, ErrorParsing,
+                                                 OptionsMap);
++      }
+ 
+       // Otherwise, look for the closest available option to report to the user
+       // in the upcoming error.
+@@ -960,8 +1313,8 @@
+ 
+     if (!Handler) {
+       if (SinkOpts.empty()) {
+-        errs() << ProgramName << ": Unknown command line argument '" << argv[i]
+-               << "'.  Try: '" << argv[0] << " -help'\n";
++        errs() << ProgramName << ": Unknown command line argument '" << Argv[i]
++               << "'.  Try: '" << Argv[0] << " -help'\n";
+ 
+         if (NearestHandler) {
+           // If we know a near match, report it as well.
+@@ -971,10 +1324,9 @@
+ 
+         ErrorParsing = true;
+       } else {
+-        for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(),
+-                                                 E = SinkOpts.end();
+-             I != E; ++I)
+-          (*I)->addOccurrence(i, "", argv[i]);
++        for (std::vector<Option*>::iterator I = SinkOpts.begin(),
++             E = SinkOpts.end(); I != E; ++I)
++          (*I)->addOccurrence(i, "", Argv[i]);
+       }
+       continue;
+     }
+@@ -984,7 +1336,7 @@
+     if (Handler->getFormattingFlag() == cl::Positional)
+       ActivePositionalArg = Handler;
+     else
+-      ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
++      ErrorParsing |= ProvideOption(Handler, ArgName, Value, Argc, Argv, i);
+   }
+ 
+   // Check and handle positional arguments now...
+@@ -992,59 +1344,85 @@
+     errs() << ProgramName
+            << ": Not enough positional command line arguments specified!\n"
+            << "Must specify at least " << NumPositionalRequired
+-           << " positional arguments: See: " << argv[0] << " -help\n";
++           << " positional arguments: See: " << Argv[0] << " -help\n";
+ 
+     ErrorParsing = true;
+   } else if (!HasUnlimitedPositionals &&
+              PositionalVals.size() > PositionalOpts.size()) {
+     errs() << ProgramName << ": Too many positional arguments specified!\n"
+            << "Can specify at most " << PositionalOpts.size()
+-           << " positional arguments: See: " << argv[0] << " -help\n";
++           << " positional arguments: See: " << Argv[0] << " -help\n";
+     ErrorParsing = true;
+ 
+   } else if (!ConsumeAfterOpt) {
+     // Positional args have already been handled if ConsumeAfter is specified.
+-    unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
++    unsigned ValNo = 0;
++    unsigned NumVals = static_cast<unsigned>(PositionalVals.size());
+     for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
+-      if (RequiresValue(PositionalOpts[i])) {
++      Option *PO = PositionalOpts[i];
++      if (RequiresValue(PO)) {
+         ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
+                                 PositionalVals[ValNo].second);
+         ValNo++;
+         --NumPositionalRequired; // We fulfilled our duty...
+       }
+ 
++      enum llvm::cl::ValueExpected VE = PO->getValueExpectedFlag();
++
++      // If it's a positional argument, provide it
++      if ((NumVals - ValNo) > NumPositionalRequired) {
++        if (VE == llvm::cl::ValuePositionalNoArgs) {
++          ProvidePositionalOption(PO, PositionalVals[ValNo].first,
++                                  PositionalVals[ValNo].second);
++          ++ValNo;
++          --NumPositionalRequired;
++          continue;
++        } else if (VE == llvm::cl::ValuePositionalWithArgs) {
++          ProvidePositionalOptionWithArgs(PO, PositionalVals[ValNo].first,
++                                          PositionalVals[ValNo].second,
++                                          ValNo,
++                                          NumPositionalRequired);
++          continue;
++        }
++      }
++
+       // If we _can_ give this option more arguments, do so now, as long as we
+       // do not give it values that others need.  'Done' controls whether the
+       // option even _WANTS_ any more.
+       //
+-      bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
+-      while (NumVals - ValNo > NumPositionalRequired && !Done) {
+-        switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
++      bool Done =
++        ((PO->getNumOccurrencesFlag() == cl::Required) &&
++         (VE != llvm::cl::ValuePositionalNoArgs));
++
++      while (((NumVals - ValNo) > NumPositionalRequired) && !Done) {
++        switch (PO->getNumOccurrencesFlag()) {
+         case cl::Optional:
+           Done = true; // Optional arguments want _at most_ one value
+         // FALL THROUGH
+         case cl::ZeroOrMore: // Zero or more will take all they can get...
+         case cl::OneOrMore:  // One or more will take all they can get...
+-          ProvidePositionalOption(PositionalOpts[i],
+-                                  PositionalVals[ValNo].first,
++          ProvidePositionalOption(PO, PositionalVals[ValNo].first,
+                                   PositionalVals[ValNo].second);
+           ValNo++;
+           break;
+         default:
+-          llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
++         assert(0 && "Internal Compiler Error: "
++                "unexpected NumOccurrences flag in "
+                            "positional argument processing!");
++         break;
+         }
+       }
+     }
+   } else {
+-    assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
++    assert(ConsumeAfterOpt && (NumPositionalRequired <= PositionalVals.size()));
+     unsigned ValNo = 0;
+-    for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
+-      if (RequiresValue(PositionalOpts[j])) {
+-        ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
+-                                                PositionalVals[ValNo].first,
++    for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j) {
++      Option *PO = PositionalOpts[j];
++      if (RequiresValue(PO)) {
++        ErrorParsing |= ProvidePositionalOption(PO, PositionalVals[ValNo].first,
+                                                 PositionalVals[ValNo].second);
+-        ValNo++;
++        ++ValNo;
++      }
+       }
+ 
+     // Handle the case where there is just one positional option, and it's
+@@ -1052,11 +1430,11 @@
+     // positional option and keep the rest for the consume after.  The above
+     // loop would have assigned no values to positional options in this case.
+     //
+-    if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
+-      ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
++    if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
++      ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
+                                               PositionalVals[ValNo].first,
+                                               PositionalVals[ValNo].second);
+-      ValNo++;
++      ++ValNo;
+     }
+ 
+     // Handle over all of the rest of the arguments to the
+@@ -1076,7 +1454,7 @@
+         Opt.second->error("must be specified at least once!");
+         ErrorParsing = true;
+       }
+-    // Fall through
++      break;
+     default:
+       break;
+     }
+@@ -1086,8 +1464,8 @@
+   // Note that if ReadResponseFiles == true, this must be done before the
+   // memory allocated for the expanded command line is free()d below.
+   DEBUG(dbgs() << "Args: ";
+-        for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
+-        dbgs() << '\n';);
++        for (int i = 0; i < Argc; ++i)
++        dbgs() << Argv[i] << ' '; dbgs() << '\n';);
+ 
+   // Free all of the memory allocated to the map.  Command line options may only
+   // be processed once!
+@@ -1119,7 +1497,8 @@
+   if (!MultiArg)
+     NumOccurrences++; // Increment the number of times we have been seen
+ 
+-  switch (getNumOccurrencesFlag()) {
++  llvm::cl::NumOccurrencesFlag NOF = getNumOccurrencesFlag();
++  switch (NOF) {
+   case Optional:
+     if (NumOccurrences > 1)
+       return error("may only occur zero or one times!", ArgName);
+@@ -1134,16 +1513,28 @@
+     break;
+   }
+ 
+-  return handleOccurrence(pos, ArgName, Value);
++  std::string SAN = ArgName;
++  std::string SV = Value;
++
++  bool R = handleOccurrence(pos, SAN.c_str(), SV.c_str());
++  return R;
++}
++
++void Option::addOccurrence() {
++  ++NumOccurrences;
+ }
+ 
+ // getValueStr - Get the value description string, using "DefaultMsg" if nothing
+ // has been specified yet.
+ //
+ static StringRef getValueStr(const Option &O, StringRef DefaultMsg) {
+-  if (O.ValueStr.empty())
++  if (!O.ValueStr)
++    return DefaultMsg;
++
++  if (O.ValueStr == '\0')
+     return DefaultMsg;
+-  return O.ValueStr;
++
++  return StringRef(O.ValueStr);
+ }
+ 
+ //===----------------------------------------------------------------------===//
+@@ -1151,7 +1542,10 @@
+ //
+ 
+ // Return the width of the option tag for printing...
+-size_t alias::getOptionWidth() const { return ArgStr.size() + 6; }
++size_t alias::getOptionWidth() const {
++  StringRef ArgStrRef(ArgStr);
++  return ArgStrRef.size() + 6;
++}
+ 
+ static void printHelpStr(StringRef HelpStr, size_t Indent,
+                          size_t FirstLineIndentedBy) {
+@@ -1166,7 +1560,8 @@
+ // Print out the option for the alias.
+ void alias::printOptionInfo(size_t GlobalWidth) const {
+   outs() << "  -" << ArgStr;
+-  printHelpStr(HelpStr, GlobalWidth, ArgStr.size() + 6);
++  StringRef ArgStrRef(ArgStr);
++  printHelpStr(HelpStr, GlobalWidth, ArgStrRef.size() + 6);
+ }
+ 
+ //===----------------------------------------------------------------------===//
+@@ -1178,7 +1573,8 @@
+ 
+ // Return the width of the option tag for printing...
+ size_t basic_parser_impl::getOptionWidth(const Option &O) const {
+-  size_t Len = O.ArgStr.size();
++  StringRef ArgStrRef(O.ArgStr);
++  size_t Len = ArgStrRef.size();
+   if (const char *ValName = getValueName())
+     Len += getValueStr(O, ValName).size() + 3;
+ 
+@@ -1190,10 +1586,28 @@
+ //
+ void basic_parser_impl::printOptionInfo(const Option &O,
+                                         size_t GlobalWidth) const {
++  const char *ArgStr = O.ArgStr ? O.ArgStr : "";
++  bool PrintValue;
++
++  if (ArgStr[0] == 'O' && ArgStr[1] == '\0')
++    PrintValue = false;
++  else if (ArgStr[0] == 'O' && std::isalpha(ArgStr[1]) && ArgStr[2] == '\0')
++    PrintValue = false;
++  else if (ArgStr[0] == 'O' && std::isdigit(ArgStr[1]) && ArgStr[2] == '\0')
++    PrintValue = false;
++  else if (ArgStr[0] == 'g' && ArgStr[1] == '\0')
++    PrintValue = false;
++  else if (ArgStr[0] == 'g' && std::isdigit(ArgStr[1]) && ArgStr[2] == '\0')
++    PrintValue = false;
++  else
++    PrintValue = true;
++
+   outs() << "  -" << O.ArgStr;
+ 
+-  if (const char *ValName = getValueName())
+-    outs() << "=<" << getValueStr(O, ValName) << '>';
++  if (const char *ValName = getValueName()) {
++    if (PrintValue)
++      outs() << "=<" << getValueStr(O, ValName) << '>';
++  }
+ 
+   printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
+ }
+@@ -1201,7 +1615,8 @@
+ void basic_parser_impl::printOptionName(const Option &O,
+                                         size_t GlobalWidth) const {
+   outs() << "  -" << O.ArgStr;
+-  outs().indent(GlobalWidth - O.ArgStr.size());
++  StringRef ArgStrRef(O.ArgStr);
++  outs().indent(GlobalWidth - ArgStrRef.size());
+ }
+ 
+ // parser<bool> implementation
+@@ -1315,7 +1730,8 @@
+ // Return the width of the option tag for printing...
+ size_t generic_parser_base::getOptionWidth(const Option &O) const {
+   if (O.hasArgStr()) {
+-    size_t Size = O.ArgStr.size() + 6;
++    StringRef ArgStrRef(O.ArgStr);
++    size_t Size = ArgStrRef.size() + 6;
+     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
+       Size = std::max(Size, std::strlen(getOption(i)) + 8);
+     return Size;
+@@ -1334,7 +1750,8 @@
+                                           size_t GlobalWidth) const {
+   if (O.hasArgStr()) {
+     outs() << "  -" << O.ArgStr;
+-    printHelpStr(O.HelpStr, GlobalWidth, O.ArgStr.size() + 6);
++    StringRef ArgStrRef(O.ArgStr);
++    printHelpStr(O.HelpStr, GlobalWidth, ArgStrRef.size() + 6);
+ 
+     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
+       size_t NumSpaces = GlobalWidth - strlen(getOption(i)) - 8;
+@@ -1342,7 +1759,8 @@
+       outs().indent(NumSpaces) << " -   " << getDescription(i) << '\n';
+     }
+   } else {
+-    if (!O.HelpStr.empty())
++    StringRef HelpStrRef(O.HelpStr);
++    if (!HelpStrRef.empty())
+       outs() << "  " << O.HelpStr << '\n';
+     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
+       const char *Option = getOption(i);
+@@ -1361,7 +1779,8 @@
+     const Option &O, const GenericOptionValue &Value,
+     const GenericOptionValue &Default, size_t GlobalWidth) const {
+   outs() << "  -" << O.ArgStr;
+-  outs().indent(GlobalWidth - O.ArgStr.size());
++  StringRef ArgStrRef(O.ArgStr);
++  outs().indent(GlobalWidth - ArgStrRef.size());
+ 
+   unsigned NumOpts = getNumOptions();
+   for (unsigned i = 0; i != NumOpts; ++i) {
+@@ -1387,7 +1806,8 @@
+ // printOptionDiff - Specializations for printing basic value types.
+ //
+ #define PRINT_OPT_DIFF(T)                                                      \
+-  void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D,      \
++  void llvm::cl::parser<T>::printOptionDiff(const Option &O, const T &V,       \
++                                            const llvm::cl::OptionValue<T> &D, \
+                                   size_t GlobalWidth) const {                  \
+     printOptionName(O, GlobalWidth);                                           \
+     std::string Str;                                                           \
+@@ -1406,6 +1826,30 @@
+     outs() << ")\n";                                                           \
+   }
+ 
++#if 0
++void
++llvm::cl::parser<bool>::printOptionDiff(const Option &O, bool V,
++                                        const llvm::cl::OptionValue<bool> &D,
++                                        size_t GlobalWidth) const {
++  printOptionName(O, GlobalWidth);
++  std::string Str;
++  {
++    raw_string_ostream SS(Str);
++    SS << V;
++  }
++  outs() << "= " << Str;
++  size_t NumSpaces =
++    MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;
++  outs().indent(NumSpaces) << " (default: ";
++  if (D.hasValue())
++    outs() << D.getValue();
++  else
++    outs() << "*no default*";
++  outs() << ")\n";
++}
++#endif
++
++
+ PRINT_OPT_DIFF(bool)
+ PRINT_OPT_DIFF(boolOrDefault)
+ PRINT_OPT_DIFF(int)
+@@ -1415,11 +1859,13 @@
+ PRINT_OPT_DIFF(float)
+ PRINT_OPT_DIFF(char)
+ 
+-void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
+-                                          OptionValue<std::string> D,
++void
++parser<std::string>::printOptionDiff(const Option &O,
++                                     const std::string &V,
++                                     const llvm::cl::OptionValue<std::string> &D,
+                                           size_t GlobalWidth) const {
+   printOptionName(O, GlobalWidth);
+-  outs() << "= " << V;
++  outs() << "= " << V.c_str();
+   size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
+   outs().indent(NumSpaces) << " (default: ";
+   if (D.hasValue())
+@@ -1439,19 +1885,21 @@
+ //===----------------------------------------------------------------------===//
+ // -help and -help-hidden option implementation
+ //
+-
+-static int OptNameCompare(const std::pair<const char *, Option *> *LHS,
+-                          const std::pair<const char *, Option *> *RHS) {
+-  return strcmp(LHS->first, RHS->first);
++template<typename Ty>
++struct OptNameCompare : public std::binary_function<Ty, Ty, bool> {
++  inline bool operator()(const Ty& LHS, const Ty& RHS) const {
++    return std::strcmp(LHS.first, RHS.first) <= 0;
+ }
++};
+ 
+ // Copy Options into a vector so we can sort them as we like.
+-static void sortOpts(StringMap<Option *> &OptMap,
+-                     SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
++static void sortOpts(llvm::cl::StdStringMap &OptMap,
++                     std::vector<std::pair<const char *, Option *>> &Opts,
+                      bool ShowHidden) {
+-  SmallPtrSet<Option *, 128> OptionSet; // Duplicate option detection.
++  SmallPtrSet<Option *, 256> OptionSet; // Duplicate option detection.
++                                        // Uh-huh. Really? Where is it used?
+ 
+-  for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
++  for (llvm::cl::StdStringMap::iterator I = OptMap.begin(), E = OptMap.end();
+        I != E; ++I) {
+     // Ignore really-hidden options.
+     if (I->second->getOptionHiddenFlag() == ReallyHidden)
+@@ -1465,21 +1913,29 @@
+     if (!OptionSet.insert(I->second).second)
+       continue;
+ 
+-    Opts.push_back(
+-        std::pair<const char *, Option *>(I->getKey().data(), I->second));
++    std::pair<const char*, Option*> KVP(I->first.c_str(), I->second);
++    Opts.push_back(KVP);
+   }
+ 
+   // Sort the options list alphabetically.
+-  array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare);
++  OptNameCompare<std::pair<const char*, Option*> >  ONC;
++  std::sort(Opts.begin(), Opts.end(), ONC);
+ }
+ 
+ namespace {
+ 
+ class HelpPrinter {
++private:
++  /// Force the allocation of storage space with suitable alignment
++  /// for this class because we use a static instance of it as
++  /// designated external storage for version option parsing (see below).
++  uint64_t B[4];
++
+ protected:
+   const bool ShowHidden;
+-  typedef SmallVector<std::pair<const char *, Option *>, 128>
++  typedef std::vector<std::pair<const char *, Option *> >
+       StrOptionPairVector;
++
+   // Print the options. Opts is assumed to be alphabetically sorted.
+   virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
+     for (size_t i = 0, e = Opts.size(); i != e; ++i)
+@@ -1487,7 +1943,11 @@
+   }
+ 
+ public:
+-  explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
++  explicit HelpPrinter(bool showHidden = false)
++  : ShowHidden(showHidden) {
++    (void) std::memset(B, 0, sizeof(B));
++  }
++
+   virtual ~HelpPrinter() {}
+ 
+   // Invoke the printer.
+@@ -1495,6 +1955,12 @@
+     if (!Value)
+       return;
+ 
++    // Get all the options,
++    std::vector<Option *> PositionalOpts;
++    std::vector<Option *> SinkOpts;
++    llvm::cl::StdStringMap OptionsMap;
++    CommandLineParser::GetOptionInfo(PositionalOpts, SinkOpts, OptionsMap);
++
+     StrOptionPairVector Opts;
+     sortOpts(GlobalParser->OptionsMap, Opts, ShowHidden);
+ 
+@@ -1503,6 +1969,12 @@
+ 
+     outs() << "USAGE: " << GlobalParser->ProgramName << " [options]";
+ 
++    // Print out the positional options.
++    Option *CAOpt = nullptr; // The cl::ConsumeAfter option, if it exists...
++    if (!PositionalOpts.empty() &&
++        PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
++      CAOpt = PositionalOpts[0];
++
+     for (auto Opt : GlobalParser->PositionalOpts) {
+       if (Opt->hasArgStr())
+         outs() << " --" << Opt->ArgStr;
+@@ -1512,6 +1984,8 @@
+     // Print the consume after option info if it exists...
+     if (GlobalParser->ConsumeAfterOpt)
+       outs() << " " << GlobalParser->ConsumeAfterOpt->HelpStr;
++    else if (CAOpt)
++      outs() << " " << CAOpt->HelpStr;
+ 
+     outs() << "\n\n";
+ 
+@@ -1531,6 +2005,11 @@
+     // Halt the program since help information was printed
+     exit(0);
+   }
++
++  void operator=(const HelpPrinter &RHS) {
++    HelpPrinter::operator=(true);
++  }
++
+ };
+ 
+ class CategorizedHelpPrinter : public HelpPrinter {
+@@ -1619,80 +2098,148 @@
+   }
+ };
+ 
+-// This wraps the Uncategorizing and Categorizing printers and decides
+-// at run time which should be invoked.
+-class HelpPrinterWrapper {
++// Declare the four HelpPrinter instances that are used to print out help, or
++// help-hidden as an uncategorized list or in categories.
++static HelpPrinter UncategorizedNormalPrinter(false);
++static HelpPrinter UncategorizedHiddenPrinter(true);
++static CategorizedHelpPrinter CategorizedNormalPrinter(false);
++static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
++
++// This wraps the Uncategorizing and Categorizing Normal printers
++// and decides at run time which should be invoked.
++// Except it doesn't work the way you think it does.
++class NormalHelpPrinterWrapper {
+ private:
+   HelpPrinter &UncategorizedPrinter;
+   CategorizedHelpPrinter &CategorizedPrinter;
+ 
+ public:
+-  explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
+-                              CategorizedHelpPrinter &CategorizedPrinter)
+-      : UncategorizedPrinter(UncategorizedPrinter),
+-        CategorizedPrinter(CategorizedPrinter) {}
++  explicit NormalHelpPrinterWrapper(HelpPrinter &UNP =
++                                    UncategorizedNormalPrinter,
++                                    CategorizedHelpPrinter &CNP =
++                                    CategorizedNormalPrinter)
++    : UncategorizedPrinter(UNP), CategorizedPrinter(CNP) { }
+ 
+   // Invoke the printer.
+   void operator=(bool Value);
++  void operator=(const NormalHelpPrinterWrapper &RHS);
++};
++
++class HiddenHelpPrinterWrapper {
++private:
++  HelpPrinter &UncategorizedPrinter;
++  CategorizedHelpPrinter &CategorizedPrinter;
++
++public:
++  explicit HiddenHelpPrinterWrapper(HelpPrinter &UHP =
++                                    UncategorizedHiddenPrinter,
++                                    CategorizedHelpPrinter &CHP =
++                                    CategorizedHiddenPrinter)
++    : UncategorizedPrinter(UHP), CategorizedPrinter(CHP) { }
++
++  // Invoke the printer.
++  void operator=(bool Value);
++  void operator=(const HiddenHelpPrinterWrapper &RHS);
+ };
+ 
+ } // End anonymous namespace
+ 
++#if 0
+ // Declare the four HelpPrinter instances that are used to print out help, or
+ // help-hidden as an uncategorized list or in categories.
+ static HelpPrinter UncategorizedNormalPrinter(false);
+ static HelpPrinter UncategorizedHiddenPrinter(true);
+ static CategorizedHelpPrinter CategorizedNormalPrinter(false);
+ static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
++#endif
+ 
+ // Declare HelpPrinter wrappers that will decide whether or not to invoke
+ // a categorizing help printer
+-static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
+-                                               CategorizedNormalPrinter);
+-static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
+-                                               CategorizedHiddenPrinter);
++static NormalHelpPrinterWrapper
++WrappedNormalPrinter(UncategorizedNormalPrinter, CategorizedNormalPrinter);
++
++static HiddenHelpPrinterWrapper
++WrappedHiddenPrinter(UncategorizedHiddenPrinter, CategorizedHiddenPrinter);
+ 
+ // Define a category for generic options that all tools should have.
+-static cl::OptionCategory GenericCategory("Generic Options");
++static cl::OptionCategory
++GenericCategory("Generic Options");
+ 
+ // Define uncategorized help printers.
+ // -help-list is hidden by default because if Option categories are being used
+ // then -help behaves the same as -help-list.
+-static cl::opt<HelpPrinter, true, parser<bool>> HLOp(
+-    "help-list",
++// static cl::opt<HelpPrinter, true, parser<bool>> HLOp(
++static cl::opt<HelpPrinter, false, parser<bool>>
++HLOp("help-list",
+     cl::desc("Display list of available options (-help-list-hidden for more)"),
+-    cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed,
++    cl::location(UncategorizedNormalPrinter), cl::Hidden,
++    cl::ValueDisallowed,
+     cl::cat(GenericCategory));
+ 
+-static cl::opt<HelpPrinter, true, parser<bool>>
+-    HLHOp("help-list-hidden", cl::desc("Display list of all available options"),
+-          cl::location(UncategorizedHiddenPrinter), cl::Hidden,
+-          cl::ValueDisallowed, cl::cat(GenericCategory));
++// static cl::opt<HelpPrinter, true, parser<bool>>
++static cl::opt<HelpPrinter, false, parser<bool>>
++HLHOp("help-list-hidden",
++      cl::desc("Display list of all available options"),
++      cl::location(UncategorizedHiddenPrinter),
++      cl::Hidden,
++      cl::ValueDisallowed,
++      cl::cat(GenericCategory));
+ 
+ // Define uncategorized/categorized help printers. These printers change their
+ // behaviour at runtime depending on whether one or more Option categories have
+ // been declared.
+-static cl::opt<HelpPrinterWrapper, true, parser<bool>>
+-    HOp("help", cl::desc("Display available options (-help-hidden for more)"),
+-        cl::location(WrappedNormalPrinter), cl::ValueDisallowed,
++// static cl::opt<HelpPrinterWrapper, true, parser<bool>>
++static cl::opt<NormalHelpPrinterWrapper, false, parser<bool>>
++HOp("help",
++    cl::desc("Display available options (-help-hidden for more)"),
++    cl::location(WrappedNormalPrinter),
++    cl::ValueDisallowed,
+         cl::cat(GenericCategory));
+ 
+-static cl::opt<HelpPrinterWrapper, true, parser<bool>>
+-    HHOp("help-hidden", cl::desc("Display all available options"),
+-         cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed,
++// static cl::opt<HelpPrinterWrapper, true, parser<bool>>
++static cl::opt<HiddenHelpPrinterWrapper, false, parser<bool>>
++HHOp("help-hidden",
++     cl::desc("Display all available options"),
++     cl::location(WrappedHiddenPrinter), cl::Hidden,
++     cl::ValueDisallowed,
+          cl::cat(GenericCategory));
+ 
+-static cl::opt<bool> PrintOptions(
+-    "print-options",
++static cl::opt<bool>
++PrintOptions("print-options",
+     cl::desc("Print non-default options after command line parsing"),
+-    cl::Hidden, cl::init(false), cl::cat(GenericCategory));
++             cl::Hidden,
++             cl::init(false),
++             cl::cat(GenericCategory));
++
++static cl::opt<bool>
++PrintAllOptions("print-all-options",
++                cl::desc("Print all option values after command line parsing"),
++                cl::Hidden,
++                cl::init(false),
++                cl::cat(GenericCategory));
+ 
+-static cl::opt<bool> PrintAllOptions(
+-    "print-all-options",
+-    cl::desc("Print all option values after command line parsing"), cl::Hidden,
+-    cl::init(false), cl::cat(GenericCategory));
++void NormalHelpPrinterWrapper::operator=(bool Value) {
++  if (!Value)
++    return;
+ 
+-void HelpPrinterWrapper::operator=(bool Value) {
++  // Decide which printer to invoke. If more than one option category is
++  // registered then it is useful to show the categorized help instead of
++  // uncategorized help.
++  if (GlobalParser->RegisteredOptionCategories.size() > 1) {
++    // unhide -help-list option so user can have uncategorized output if they
++    // want it.
++    HLOp.setHiddenFlag(NotHidden);
++
++    CategorizedPrinter = true; // Invoke categorized printer
++  } else
++    UncategorizedPrinter = true; // Invoke uncategorized printer
++}
++
++void NormalHelpPrinterWrapper::operator=(const NormalHelpPrinterWrapper &RHS) {
++  NormalHelpPrinterWrapper::operator=(true);
++}
++
++void HiddenHelpPrinterWrapper::operator=(bool Value) {
+   if (!Value)
+     return;
+ 
+@@ -1709,14 +2256,20 @@
+     UncategorizedPrinter = true; // Invoke uncategorized printer
+ }
+ 
++void HiddenHelpPrinterWrapper::operator=(const HiddenHelpPrinterWrapper &RHS) {
++  HiddenHelpPrinterWrapper::operator=(true);
++}
++
+ // Print the value of each option.
+-void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
++void cl::PrintOptionValues() { GlobalParser->PrintOptionValues(); }
+ 
+-void CommandLineParser::printOptionValues() {
++void CommandLineParser::PrintOptionValues() {
+   if (!PrintOptions && !PrintAllOptions)
+     return;
+ 
+-  SmallVector<std::pair<const char *, Option *>, 128> Opts;
++  GetOptionInfo(PositionalOpts, SinkOpts, OptionsMap);
++
++  std::vector<std::pair<const char *, Option *> > Opts;
+   sortOpts(OptionsMap, Opts, /*ShowHidden*/ true);
+ 
+   // Compute the maximum argument length...
+@@ -1732,35 +2285,51 @@
+ 
+ static std::vector<void (*)()> *ExtraVersionPrinters = nullptr;
+ 
+-namespace {
++namespace llvm {
++  namespace cl {
+ class VersionPrinter {
++    private:
++      /// Force the allocation of storage space with suitable alignment
++      /// for this class because we use a static instance of it as
++      /// designated external storage for version option parsing (see below).
++      uint64_t B[4];
++
+ public:
++      VersionPrinter() {
++        (void) std::memset(B, 0, sizeof(B));
++      }
++
++      static VersionPrinter &instance();
++
+   void print() {
+     raw_ostream &OS = outs();
+-    OS << "LLVM (http://llvm.org/):\n"
++        std::cout << "LLVM (http://llvm.org/):\n"
+        << "  " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
+ #ifdef LLVM_VERSION_INFO
+-    OS << " " << LLVM_VERSION_INFO;
++        std::cout < " " << LLVM_VERSION_INFO;
+ #endif
+-    OS << "\n  ";
++        std::cout << "\n  ";
+ #ifndef __OPTIMIZE__
+-    OS << "DEBUG build";
++        std::cout << "DEBUG build";
+ #else
+-    OS << "Optimized build";
++        std::cout << "Optimized build";
+ #endif
+ #ifndef NDEBUG
+-    OS << " with assertions";
++        std::cout << " with assertions";
+ #endif
+     std::string CPU = sys::getHostCPUName();
+     if (CPU == "generic")
+       CPU = "(unknown)";
+-    OS << ".\n"
++
++        std::cout << ".\n"
++
+ #if (ENABLE_TIMESTAMPS == 1)
+        << "  Built " << __DATE__ << " (" << __TIME__ << ").\n"
+ #endif
+        << "  Default target: " << sys::getDefaultTargetTriple() << '\n'
+        << "  Host CPU: " << CPU << '\n';
+   }
++
+   void operator=(bool OptionWasSpecified) {
+     if (!OptionWasSpecified)
+       return;
+@@ -1769,33 +2338,42 @@
+       (*OverrideVersionPrinter)();
+       exit(0);
+     }
++
+     print();
+ 
+-    // Iterate over any registered extra printers and call them to add further
+-    // information.
++        // Iterate over any registered extra printers and call them
++        // to add further information.
+     if (ExtraVersionPrinters != nullptr) {
+-      outs() << '\n';
+-      for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
+-                                             E = ExtraVersionPrinters->end();
++          std::cout << std::endl;
++          for (std::vector<void (*)()>::iterator I =
++               ExtraVersionPrinters->begin(), E = ExtraVersionPrinters->end();
+            I != E; ++I)
+         (*I)();
+     }
+ 
+     exit(0);
+   }
++
++      void operator=(const VersionPrinter &RHS) {
++        VersionPrinter::operator=(true);
++      }
+ };
+-} // End anonymous namespace
++  } // end namespace cl
++} // End namespace llvm
+ 
+ // Define the --version option that prints out the LLVM version for the tool
+-static VersionPrinter VersionPrinterInstance;
++static llvm::cl::VersionPrinter VersionPrinterInstance;
+ 
+-static cl::opt<VersionPrinter, true, parser<bool>>
+-    VersOp("version", cl::desc("Display the version of this program"),
+-           cl::location(VersionPrinterInstance), cl::ValueDisallowed,
+-           cl::cat(GenericCategory));
++static
++cl::opt<llvm::cl::VersionPrinter, false, parser<bool> >
++VersOp("version", cl::desc("Display the version of this program"),
++       cl::location(VersionPrinterInstance),
++       cl::ValueRequired,
++       cl::cat(GenericCategory));
+ 
+ // Utility function for printing the help message.
+ void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
++
+   // This looks weird, but it actually prints the help message. The Printers are
+   // types of HelpPrinter and the help gets printed when its operator= is
+   // invoked. That's because the "normal" usages of the help printer is to be
+@@ -1814,7 +2392,9 @@
+ }
+ 
+ /// Utility function for printing version number.
+-void cl::PrintVersionMessage() { VersionPrinterInstance.print(); }
++void cl::PrintVersionMessage() {
++  VersionPrinterInstance.print();
++}
+ 
+ void cl::SetVersionPrinter(void (*func)()) { OverrideVersionPrinter = func; }
+ 
+@@ -1826,7 +2406,16 @@
+ }
+ 
+ StringMap<Option *> &cl::getRegisteredOptions() {
+-  return GlobalParser->OptionsMap;
++
++  GlobalParser->ReturnOptionsMap.clear();
++  for (llvm::cl::StdStringMap::const_iterator I =
++       GlobalParser->OptionsMap.begin(), E = GlobalParser->OptionsMap.end();
++       I != E; ++I) {
++    GlobalParser->ReturnOptionsMap.insert(std::make_pair((*I).first.c_str(),
++                                                         (*I).second));
++  }
++
++  return GlobalParser->ReturnOptionsMap;
+ }
+ 
+ void cl::HideUnrelatedOptions(cl::OptionCategory &Category) {
+@@ -1852,3 +2441,4 @@
+                                  const char *Overview) {
+   llvm::cl::ParseCommandLineOptions(argc, argv, Overview);
+ }
++
+###
+--- lib/Support/Options.cpp	2014-10-15 14:54:35.000000000 -0700
++++ lib/Support/Options.cpp	2016-05-14 12:34:43.808666693 -0700
+@@ -24,8 +24,9 @@
+ 
+ void OptionRegistry::addOption(void *Key, cl::Option *O) {
+   assert(Options.find(Key) == Options.end() &&
+-         "Argument with this key already registerd");
++         "Argument with this key already registered");
+   Options.insert(std::make_pair(Key, O));
++  O->addOccurrence();
+ }
+ 
+ static ManagedStatic<OptionRegistry> OR;
+###
+--- include/llvm/Support/RandomNumberGenerator.h	2015-06-23 01:49:53.000000000 -0800
++++ include/llvm/Support/RandomNumberGenerator.h	2016-07-05 06:13:50.168003475 -0800
+@@ -32,7 +32,11 @@
+ class RandomNumberGenerator {
+ public:
+   /// Returns a random number in the range [0, Max).
+-  uint_fast64_t operator()();
++  uint64_t operator()();
++
++  /// Workaround for static global initialization order in shared
++  /// libraries in Solaris. Solaris ld does not support init_priority.
++  static bool Initialize();
+ 
+ private:
+   /// Seeds and salts the underlying RNG engine.
+###
+--- lib/Support/RandomNumberGenerator.cpp	2015-03-23 10:19:41.000000000 -0800
++++ lib/Support/RandomNumberGenerator.cpp	2016-07-05 18:49:45.063365340 -0800
+@@ -20,19 +20,45 @@
+ 
+ using namespace llvm;
+ 
++#include <chrono>
++
+ #define DEBUG_TYPE "rng"
+ 
++
+ // Tracking BUG: 19665
+ // http://llvm.org/bugs/show_bug.cgi?id=19665
+ //
+-// Do not change to cl::opt<uint64_t> since this silently breaks argument parsing.
+-static cl::opt<unsigned long long>
+-Seed("rng-seed", cl::value_desc("seed"),
+-     cl::desc("Seed for the random number generator"), cl::init(0));
++// Do not change to cl::opt<uint64_t> since this silently breaks
++// argument parsing.
++static llvm::cl::opt<unsigned long long>
++Seed(cl::Prefix, "rng-seed",
++     cl::desc("Seed for the random number generator"),
++     cl::value_desc("seed"),
++     cl::NotHidden,
++     cl::Optional,
++     cl::init(0ULL),
++     cl::ValueRequired);
++
++static bool InitFirst = false;
++
++bool __attribute__((noinline))
++RandomNumberGenerator::Initialize() {
++  auto Now = std::chrono::system_clock::now();
++  Seed.setValue(static_cast<unsigned long long>(
++      std::chrono::system_clock::to_time_t(Now)));
++  return true;
++}
++
++RandomNumberGenerator::RandomNumberGenerator(StringRef Salt)
++  : Generator() {
++  if (!InitFirst) {
++    InitFirst = RandomNumberGenerator::Initialize();
++    if (!InitFirst)
++      llvm_unreachable("Static initialization failed!");
++  }
+ 
+-RandomNumberGenerator::RandomNumberGenerator(StringRef Salt) {
+   DEBUG(
+-    if (Seed == 0)
++    if (Seed.getValue() == 0ULL)
+       dbgs() << "Warning! Using unseeded random number generator.\n"
+   );
+ 
+@@ -42,9 +68,10 @@
+   // are using a 64-bit RNG. This isn't a problem since the Mersenne
+   // twister constructor copies these correctly into its initial state.
+   std::vector<uint32_t> Data;
+-  Data.reserve(2 + Salt.size());
+-  Data.push_back(Seed);
+-  Data.push_back(Seed >> 32);
++  Data.resize(2 + Salt.size());
++  unsigned long long V = Seed.getValue();
++  Data.push_back(V);
++  Data.push_back(V >> 32);
+ 
+   std::copy(Salt.begin(), Salt.end(), Data.end());
+ 
+@@ -52,6 +79,7 @@
+   Generator.seed(SeedSeq);
+ }
+ 
+-uint_fast64_t RandomNumberGenerator::operator()() {
+-  return Generator();
++uint64_t RandomNumberGenerator::operator()() {
++  return static_cast<uint64_t>(Generator());
+ }
++
+###
+--- lib/Support/Unix/Path.inc	2015-11-02 09:57:24.000000000 -0500
++++ lib/Support/Unix/Path.inc	2016-05-22 16:56:44.390780570 -0400
+@@ -469,7 +469,7 @@
+ 
+ std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
+                                                 StringRef path){
+-  SmallString<128> path_null(path);
++  SmallString<PATH_MAX> path_null(path);
+   DIR *directory = ::opendir(path_null.c_str());
+   if (!directory)
+     return std::error_code(errno, std::generic_category());
+@@ -484,8 +484,10 @@
+ std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
+   if (it.IterationHandle)
+     ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
++
+   it.IterationHandle = 0;
+-  it.CurrentEntry = directory_entry();
++  directory_entry de;
++  it.CurrentEntry = de;
+   return std::error_code();
+ }
+ 
+###
+--- include/llvm/Support/FileSystem.h	2015-11-05 20:45:30.000000000 -0500
++++ include/llvm/Support/FileSystem.h	2016-05-22 20:58:26.603743052 -0400
+@@ -695,15 +695,43 @@
+   mutable file_status Status;
+ 
+ public:
+-  explicit directory_entry(const Twine &path, file_status st = file_status())
+-    : Path(path.str())
+-    , Status(st) {}
++  explicit directory_entry(const Twine &path, file_status ST = file_status())
++    : Path(path.str()), Status(ST) { }
+ 
+-  directory_entry() {}
++  directory_entry() : Path(""), Status(file_status()) { }
+ 
+-  void assign(const Twine &path, file_status st = file_status()) {
++  directory_entry(const directory_entry &RHS)
++    : Path(RHS.Path), Status(RHS.Status) { }
++
++  directory_entry(directory_entry &&RHS)
++    : Path(""), Status(file_status()) {
++      Path = std::move(RHS.Path);
++      Status = std::move(RHS.Status);
++    }
++
++  ~directory_entry() { }
++
++  directory_entry &operator=(const directory_entry &rhs) {
++    if (this != &rhs) {
++      Path = rhs.Path;
++      Status = rhs.Status;
++    }
++
++    return *this;
++  }
++
++  const directory_entry &operator=(directory_entry &&rhs) {
++    if (this != &rhs) {
++      Path = std::move(rhs.Path);
++      Status = std::move(rhs.Status);
++    }
++
++    return *this;
++  }
++
++  void assign(const Twine &path, file_status ST = file_status()) {
+     Path = path.str();
+-    Status = st;
++    Status = ST;
+   }
+ 
+   void replace_filename(const Twine &filename, file_status st = file_status());
+###
+--- include/llvm/Support/PluginLoader.h	2015-06-23 05:49:53.000000000 -0400
++++ include/llvm/Support/PluginLoader.h	2016-05-08 23:19:20.527430631 -0400
+@@ -22,6 +22,9 @@
+ namespace llvm {
+   struct PluginLoader {
+     void operator=(const std::string &Filename);
++    bool operator==(const std::string &Filename) const;
++    bool operator!=(const std::string &Filename) const;
++
+     static unsigned getNumPlugins();
+     static std::string& getPlugin(unsigned num);
+   };
+###
+--- include/llvm/Support/Process.h	2015-06-23 05:49:53.000000000 -0400
++++ include/llvm/Support/Process.h	2016-05-08 23:19:20.527430631 -0400
+@@ -88,6 +88,12 @@
+                     ArrayRef<const char *> ArgsFromMain,
+                     SpecificBumpPtrAllocator<char> &ArgAllocator);
+ 
++  /// Overload the above for a std::vector, and without the
++  /// useless SpecificBumpPtrAllocator argument.
++  static std::error_code
++  GetArgumentVector(std::vector<const char *> &ArgsOut,
++                    ArrayRef<const char *> ArgsIn);
++
+   // This functions ensures that the standard file descriptors (input, output,
+   // and error) are properly mapped to a file descriptor before we use any of
+   // them.  This should only be called by standalone programs, library
+###
+--- include/llvm/Support/ThreadLocal.h	2015-06-23 02:49:53.000000000 -0700
++++ include/llvm/Support/ThreadLocal.h	2016-05-24 18:32:55.335317270 -0700
+@@ -28,10 +28,8 @@
+       ///
+       /// This is embedded in the class and we avoid malloc'ing/free'ing it,
+       /// to make this class more safe for use along with CrashRecoveryContext.
+-      union {
+-        char data[sizeof(ThreadLocalDataTy)];
+-        ThreadLocalDataTy align_data;
+-      };
++      uint64_t data[2];
++
+     public:
+       ThreadLocalImpl();
+       virtual ~ThreadLocalImpl();
+@@ -42,7 +40,7 @@
+ 
+     /// ThreadLocal - A class used to abstract thread-local storage.  It holds,
+     /// for each thread, a pointer a single object of type T.
+-    template<class T>
++    template<typename T>
+     class ThreadLocal : public ThreadLocalImpl {
+     public:
+       ThreadLocal() : ThreadLocalImpl() { }
+###
+--- lib/Support/ThreadLocal.cpp	2014-12-14 17:19:53.000000000 -0800
++++ lib/Support/ThreadLocal.cpp	2016-05-24 18:36:15.908033311 -0700
+@@ -15,6 +15,8 @@
+ #include "llvm/Support/Compiler.h"
+ #include "llvm/Support/ThreadLocal.h"
+ 
++#include <cstring>
++
+ //===----------------------------------------------------------------------===//
+ //=== WARNING: Implementation here must contain only TRULY operating system
+ //===          independent code.
+@@ -24,17 +26,24 @@
+ // Define all methods as no-ops if threading is explicitly disabled
+ namespace llvm {
+ using namespace sys;
+-ThreadLocalImpl::ThreadLocalImpl() : data() { }
++
++ThreadLocalImpl::ThreadLocalImpl() {
++  (void) std::memset(data, 0, sizeof(data));
++}
++
+ ThreadLocalImpl::~ThreadLocalImpl() { }
++
+ void ThreadLocalImpl::setInstance(const void* d) {
+   static_assert(sizeof(d) <= sizeof(data), "size too big");
+   void **pd = reinterpret_cast<void**>(&data);
+   *pd = const_cast<void*>(d);
+ }
++
+ void *ThreadLocalImpl::getInstance() {
+   void **pd = reinterpret_cast<void**>(&data);
+   return *pd;
+ }
++
+ void ThreadLocalImpl::removeInstance() {
+   setInstance(nullptr);
+ }
+###
+--- include/llvm/Support/BranchProbability.h	2015-12-22 09:56:14.000000000 -0900
++++ include/llvm/Support/BranchProbability.h	2016-07-07 09:50:50.352228870 -0800
+@@ -29,6 +29,7 @@
+ // denominator is always a constant value (here we use 1<<31 for maximum
+ // precision).
+ class BranchProbability {
++private:
+   // Numerator
+   uint32_t N;
+ 
+@@ -38,12 +39,32 @@
+ 
+   // Construct a BranchProbability with only numerator assuming the denominator
+   // is 1<<31. For internal use only.
+-  explicit BranchProbability(uint32_t n) : N(n) {}
++  explicit BranchProbability(uint32_t n) : N(n) { }
+ 
+ public:
+-  BranchProbability() : N(UnknownN) {}
++  BranchProbability() : N(UnknownN) { }
+   BranchProbability(uint32_t Numerator, uint32_t Denominator);
+ 
++  // If we are using this class in STL containers (such as std::vector),
++  // and we are indeed doing that (see CodeGen/MachineBasicBlock.cpp),
++  // then this class must satisfiy MoveInsertable, CopyInsertable and
++  // DefaultInsertable.
++  BranchProbability(const BranchProbability &RHS) : N(RHS.N) { }
++  BranchProbability(BranchProbability &&RHS) : N(std::move(RHS.N)) { }
++  BranchProbability &operator=(const BranchProbability &RHS) {
++    if (this != &RHS)
++      N = RHS.N;
++    return *this;
++  }
++
++  const BranchProbability &operator=(BranchProbability &&RHS) {
++    if (this != &RHS)
++      N = std::move(RHS.N);
++    return *this;
++  }
++
++  ~BranchProbability() { }
++
+   bool isZero() const { return N == 0; }
+   bool isUnknown() const { return N == UnknownN; }
+ 
+###.
+--- lib/Support/Host.cpp	2015-12-15 08:35:29.000000000 -0500
++++ lib/Support/Host.cpp	2016-05-08 23:19:20.536430850 -0400
+@@ -39,6 +39,11 @@
+ #include <mach/machine.h>
+ #endif
+ 
++#if defined(__sun__)
++#include <cstring>
++#include <kstat.h>
++#endif
++
+ #define DEBUG_TYPE "host-detection"
+ 
+ //===----------------------------------------------------------------------===//
+@@ -733,6 +738,42 @@
+   
+   return "generic";
+ }
++#elif defined(__sun__) && defined(__sparc__)
++StringRef sys::getHostCPUName() {
++  kstat_ctl_t *KC = 0;
++  kstat_t *KSP = 0;
++  kstat_named_t *KNP = 0;
++  static char Buffer[256];
++  static bool Init = false;
++  const char *Value;
++
++  if (!Init) {
++    KC = kstat_open();
++    if (KC) {
++      KSP = kstat_lookup(KC, "cpu_info", -1, "cpu_info0");
++      kstat_read(KC, KSP, NULL);
++      KNP = reinterpret_cast<kstat_named_t*>(kstat_data_lookup(KSP, "brand"));
++      Value = (const char *) KNP->value.str.addr.ptr;
++      (void) std::sprintf(Buffer, "%s (", Value);
++
++      KNP =
++        reinterpret_cast<kstat_named_t*>(kstat_data_lookup(KSP, "cpu_type"));
++      Value = (const char*) KNP->value.c;
++      (void) std::strcat(Buffer, Value);
++      (void) std::strcat(Buffer, ") ");
++
++      KNP =
++        reinterpret_cast<kstat_named_t*>(kstat_data_lookup(KSP,
++                                                           "implementation"));
++      Value = (const char*) KNP->value.str.addr.ptr;
++      (void) std::strcat(Buffer, Value);
++      Init = true;
++      kstat_close(KC);
++    }
++  }
++
++  return Buffer;
++}
+ #else
+ StringRef sys::getHostCPUName() {
+   return "generic";
+--- lib/Support/MemoryBuffer.cpp	2015-10-14 21:27:19.000000000 -0400
++++ lib/Support/MemoryBuffer.cpp	2016-05-08 23:19:20.536430850 -0400
+@@ -32,6 +32,9 @@
+ #else
+ #include <io.h>
+ #endif
++
++#include <climits>
++
+ using namespace llvm;
+ 
+ //===----------------------------------------------------------------------===//
+@@ -70,7 +73,7 @@
+ }
+ 
+ void *operator new(size_t N, const NamedBufferAlloc &Alloc) {
+-  SmallString<256> NameBuf;
++  SmallString<PATH_MAX> NameBuf;
+   StringRef NameRef = Alloc.Name.toStringRef(NameBuf);
+ 
+   char *Mem = static_cast<char *>(operator new(N + NameRef.size() + 1));
+@@ -132,7 +135,7 @@
+   // that MemoryBuffer and data are aligned so PointerIntPair works with them.
+   // TODO: Is 16-byte alignment enough?  We copy small object files with large
+   // alignment expectations into this buffer.
+-  SmallString<256> NameBuf;
++  SmallString<PATH_MAX> NameBuf;
+   StringRef NameRef = BufferName.toStringRef(NameBuf);
+   size_t AlignedStringLen =
+       RoundUpToAlignment(sizeof(MemoryBufferMem) + NameRef.size() + 1, 16);
+@@ -164,7 +167,7 @@
+ ErrorOr<std::unique_ptr<MemoryBuffer>>
+ MemoryBuffer::getFileOrSTDIN(const Twine &Filename, int64_t FileSize,
+                              bool RequiresNullTerminator) {
+-  SmallString<256> NameBuf;
++  SmallString<PATH_MAX> NameBuf;
+   StringRef NameRef = Filename.toStringRef(NameBuf);
+ 
+   if (NameRef == "-")
+--- lib/Support/PluginLoader.cpp	2012-12-03 11:50:05.000000000 -0500
++++ lib/Support/PluginLoader.cpp	2016-05-08 23:19:20.536430850 -0400
+@@ -34,6 +34,21 @@
+   }
+ }
+ 
++bool PluginLoader::operator==(const std::string &Filename) const {
++  sys::SmartScopedLock<true> Lock(*PluginsLock);
++  for (std::vector<std::string>::const_iterator I = Plugins->begin(),
++       E = Plugins->end(); I != E; ++I) {
++    if (*I == Filename)
++      return true;
++  }
++
++  return false;
++}
++
++bool PluginLoader::operator!=(const std::string &Filename) const {
++  return !this->operator==(Filename);
++}
++
+ unsigned PluginLoader::getNumPlugins() {
+   sys::SmartScopedLock<true> Lock(*PluginsLock);
+   return Plugins.isConstructed() ? Plugins->size() : 0;
+###
+--- lib/Support/SmallVector.cpp	2015-06-09 02:47:46.000000000 -0700
++++ lib/Support/SmallVector.cpp	2016-05-23 11:37:44.177294041 -0700
+@@ -11,9 +11,13 @@
+ //
+ //===----------------------------------------------------------------------===//
+ 
++#include "llvm/Support/MathExtras.h"
++#include "llvm/Support/raw_ostream.h"
+ #include "llvm/ADT/SmallVector.h"
+ using namespace llvm;
+ 
++#include <stdlib.h>
++
+ /// grow_pod - This is an implementation of the grow() method which only works
+ /// on POD-like datatypes and is out of line to reduce code duplication.
+ void SmallVectorBase::grow_pod(void *FirstEl, size_t MinSizeInBytes,
+@@ -23,15 +27,41 @@
+   if (NewCapacityInBytes < MinSizeInBytes)
+     NewCapacityInBytes = MinSizeInBytes;
+ 
++  NewCapacityInBytes =
++    llvm::RoundUpToAlignment(NewCapacityInBytes, llvm::alignOf<uint64_t>());
++
+   void *NewElts;
++  size_t Alignment = llvm::alignOf<uint64_t>();
+   if (BeginX == FirstEl) {
+-    NewElts = malloc(NewCapacityInBytes);
++#if defined(_MSC_VER)
++    NewElts = _aligned_malloc(Alignment, NewCapacityInBytes);
++    assert(NewElts && "_aligned_malloc failed!");
++#else
++    int R = posix_memalign(&NewElts, Alignment, NewCapacityInBytes);
++    assert((R == 0) && "posix_memalign failed!");
++#endif
++
++    assert(NewElts && "Invalid pointer after aligned allocation!");
++    (void) std::memset(NewElts, 0, NewCapacityInBytes);
+ 
+     // Copy the elements over.  No need to run dtors on PODs.
+-    memcpy(NewElts, this->BeginX, CurSizeBytes);
++    (void) std::memcpy(NewElts, this->BeginX, CurSizeBytes);
+   } else {
+     // If this wasn't grown from the inline copy, grow the allocated space.
+-    NewElts = realloc(this->BeginX, NewCapacityInBytes);
++#if defined(_MSC_VER)
++    NewElts = _aligned_malloc(Alignment, NewCapacityInBytes);
++    assert(NewElts && "_aligned_malloc failed!");
++#else
++    int R = posix_memalign(&NewElts, Alignment, NewCapacityInBytes);
++    assert((R == 0) && "posix_memalign failed!");
++#endif
++
++    assert(NewElts && "Invalid pointer after aligned allocation!");
++    (void) std::memset(NewElts, 0, NewCapacityInBytes);
++
++    // Copy the elements over.  No need to run dtors on PODs.
++    (void) std::memcpy(NewElts, this->BeginX, CurSizeBytes);
++    std::free(this->BeginX);
+   }
+   assert(NewElts && "Out of memory");
+ 
+@@ -39,3 +69,4 @@
+   this->BeginX = NewElts;
+   this->CapacityX = (char*)this->BeginX + NewCapacityInBytes;
+ }
++
+###
+--- lib/Support/Unix/Process.inc	2015-12-11 17:52:32.000000000 -0500
++++ lib/Support/Unix/Process.inc	2016-05-08 23:19:20.537430874 -0400
+@@ -188,6 +188,14 @@
+   return std::error_code();
+ }
+ 
++std::error_code
++Process::GetArgumentVector(std::vector<const char *> &ArgsOut,
++                           ArrayRef<const char *> ArgsIn) {
++  ArgsOut.insert(ArgsOut.end(), ArgsIn.begin(), ArgsIn.end());
++
++  return std::error_code();
++}
++
+ namespace {
+ class FDCloser {
+ public:
+--- lib/Support/Unix/Program.inc	2016-01-05 14:56:12.000000000 -0500
++++ lib/Support/Unix/Program.inc	2016-05-08 23:19:20.537430874 -0400
+@@ -40,9 +40,6 @@
+ #include <unistd.h>
+ #endif
+ #ifdef HAVE_POSIX_SPAWN
+-#ifdef __sun__
+-#define  _RESTRICT_KYWD
+-#endif
+ #include <spawn.h>
+ 
+ #if defined(__APPLE__)
+###
+--- include/llvm/LinkAllPasses.h	2016-01-13 10:37:51.000000000 -0900
++++ include/llvm/LinkAllPasses.h	2016-07-06 07:55:00.479529980 -0800
+@@ -43,18 +43,24 @@
+ #include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
+ #include "llvm/Transforms/Vectorize.h"
+ #include "llvm/Support/Valgrind.h"
++
+ #include <cstdlib>
+ 
+-namespace {
+-  struct ForcePassLinking {
++namespace llvm {
++  class ForcePassLinking {
++  public:
+     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.
++      // Except for the fact that your theory doesn't work.
+       if (std::getenv("bar") != (char*) -1)
+         return;
+ 
++      // Hi, GCC. Please don't throw this function away.
++      asm("");
++
+       (void) llvm::createAAEvalPass();
+       (void) llvm::createAggressiveDCEPass();
+       (void) llvm::createBitTrackingDCEPass();
+@@ -160,11 +166,13 @@
+       (void) llvm::createPostOrderFunctionAttrsPass();
+       (void) llvm::createReversePostOrderFunctionAttrsPass();
+       (void) llvm::createMergeFunctionsPass();
+-      std::string buf;
+-      llvm::raw_string_ostream os(buf);
+-      (void) llvm::createPrintModulePass(os);
+-      (void) llvm::createPrintFunctionPass(os);
+-      (void) llvm::createPrintBasicBlockPass(os);
++
++      std::string S;
++      llvm::raw_string_ostream RSO(S);
++      (void) llvm::createPrintModulePass(RSO);
++      (void) llvm::createPrintFunctionPass(RSO);
++      (void) llvm::createPrintBasicBlockPass(RSO);
++
+       (void) llvm::createModuleDebugInfoPrinterPass();
+       (void) llvm::createPartialInliningPass();
+       (void) llvm::createLintPass();
+@@ -186,17 +194,39 @@
+       (void) llvm::createFloat2IntPass();
+       (void) llvm::createEliminateAvailableExternallyPass();
+ 
+-      (void)new llvm::IntervalPartition();
+-      (void)new llvm::ScalarEvolutionWrapperPass();
+-      llvm::Function::Create(nullptr, llvm::GlobalValue::ExternalLinkage)->viewCFGOnly();
++      llvm::IntervalPartition *LIP = new llvm::IntervalPartition();
++      (void) LIP;
++
++      llvm::ScalarEvolutionWrapperPass *LSE =
++        new llvm::ScalarEvolutionWrapperPass();
++      (void) LSE;
++
++      llvm::Function *F =
++        llvm::Function::Create(nullptr, llvm::GlobalValue::ExternalLinkage);
++      (void) F;
++      F->viewCFGOnly();
++
+       llvm::RGPassManager RGM;
+       llvm::AliasAnalysis AA;
+       llvm::AliasSetTracker X(AA);
+       X.add(nullptr, 0, llvm::AAMDNodes()); // for -print-alias-sets
+-      (void) llvm::AreStatisticsEnabled();
+-      (void) llvm::sys::RunningOnValgrind();
++
++      bool B1 = llvm::AreStatisticsEnabled();
++      (void) B1;
++      bool B2 = llvm::sys::RunningOnValgrind();
++      (void) B1;
+     }
+-  } ForcePassLinking; // Force link by creating a global definition.
++
++    ~ForcePassLinking() { }
++
++  private:
++    /// Initialization of this is done in lib/CodeGen/Passes.cpp
++    /// because of initialization ordering problems with global
++    /// static variables.  The design of this static initialization
++    /// dependency chain is completely broken.
++    static ForcePassLinking *FPL;
++  };
+ }
+ 
+ #endif
++
+ 
+ 
--- a/components/llvm/patches/003-Makefile.rules.patch	Thu Jul 28 16:15:45 2016 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,18 +0,0 @@
-# Strip unused sections in Solaris.
-# https://llvm.org/bugs/show_bug.cgi?id=24641
---- Makefile.rules	2014-11-04 16:35:15.000000000 -0800
-+++ Makefile.rules	2015-07-17 18:28:25.379220132 -0700
-@@ -638,9 +638,12 @@
-   ifeq ($(HOST_OS),Darwin)
-     LD.Flags += -Wl,-dead_strip
-   else
--    ifneq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW))
-+    ifneq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW SunOS))
-       LD.Flags += -Wl,--gc-sections
-     endif
-+    ifeq ($(HOST_OS), $(filter $(HOST_OS), SunOS))
-+      LD.Flags += -Wl,-z -Wl,discard-unused=sections
-+    endif
-   endif
- endif
- 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/003-solaris-LLVM-ADT.patch	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,494 @@
+# 24312028 llvm::Twine needs copy constructors and assignment operators
+# 3.9.X for upstream.
+--- include/llvm/ADT/DenseMap.h	2015-10-01 20:46:33.000000000 -0400
++++ include/llvm/ADT/DenseMap.h	2016-05-08 23:19:20.512430267 -0400
+@@ -854,7 +854,8 @@
+ 
+       // First move the inline buckets into a temporary storage.
+       AlignedCharArrayUnion<BucketT[InlineBuckets]> TmpStorage;
+-      BucketT *TmpBegin = reinterpret_cast<BucketT *>(TmpStorage.buffer);
++      BucketT *TmpBegin =
++        reinterpret_cast<BucketT*>(reinterpret_cast<void*>(TmpStorage.buffer));
+       BucketT *TmpEnd = TmpBegin;
+ 
+       // Loop over the buckets, moving non-empty, non-tombstones into the
+@@ -938,7 +939,8 @@
+     // 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);
++    return reinterpret_cast<const BucketT*>(
++      reinterpret_cast<const void*>(storage.buffer));
+   }
+   BucketT *getInlineBuckets() {
+     return const_cast<BucketT *>(
+@@ -947,8 +949,10 @@
+   const LargeRep *getLargeRep() const {
+     assert(!Small);
+     // Note, same rule about aliasing as with getInlineBuckets.
+-    return reinterpret_cast<const LargeRep *>(storage.buffer);
++    return reinterpret_cast<const LargeRep*>(
++      reinterpret_cast<const void*>(storage.buffer));
+   }
++
+   LargeRep *getLargeRep() {
+     return const_cast<LargeRep *>(
+       const_cast<const SmallDenseMap *>(this)->getLargeRep());
+--- include/llvm/ADT/Optional.h	2015-08-19 19:07:27.000000000 -0400
++++ include/llvm/ADT/Optional.h	2016-05-08 23:19:20.513430291 -0400
+@@ -116,17 +116,39 @@
+     reset();
+   }
+ 
+-  const T* getPointer() const { assert(hasVal); return reinterpret_cast<const T*>(storage.buffer); }
+-  T* getPointer() { assert(hasVal); return reinterpret_cast<T*>(storage.buffer); }
+-  const T& getValue() const LLVM_LVALUE_FUNCTION { assert(hasVal); return *getPointer(); }
+-  T& getValue() LLVM_LVALUE_FUNCTION { assert(hasVal); return *getPointer(); }
++  const T* getPointer() const {
++    assert(hasVal);
++    return reinterpret_cast<const T*>(storage.buffer);
++  }
++
++  T* getPointer() {
++    assert(hasVal);
++    return reinterpret_cast<T*>(storage.buffer);
++  }
++
++  const T& getValue() const LLVM_LVALUE_FUNCTION {
++    assert(hasVal);
++    return *getPointer();
++  }
++
++  T& getValue() LLVM_LVALUE_FUNCTION {
++    assert(hasVal);
++    return *getPointer();
++  }
+ 
+   explicit operator bool() const { return hasVal; }
+   bool hasValue() const { return hasVal; }
+   const T* operator->() const { return getPointer(); }
+   T* operator->() { return getPointer(); }
+-  const T& operator*() const LLVM_LVALUE_FUNCTION { assert(hasVal); return *getPointer(); }
+-  T& operator*() LLVM_LVALUE_FUNCTION { assert(hasVal); return *getPointer(); }
++  const T& operator*() const LLVM_LVALUE_FUNCTION {
++    assert(hasVal);
++    return *getPointer();
++  }
++
++  T& operator*() LLVM_LVALUE_FUNCTION {
++    assert(hasVal);
++    return *getPointer();
++  }
+ 
+   template <typename U>
+   LLVM_CONSTEXPR T getValueOr(U &&value) const LLVM_LVALUE_FUNCTION {
+--- include/llvm/ADT/Triple.h	2015-12-01 02:33:56.000000000 -0800
++++ include/llvm/ADT/Triple.h	2016-05-09 07:12:20.705509490 -0700
+@@ -127,6 +127,7 @@
+     MipsTechnologies,
+     NVIDIA,
+     CSR,
++    Sun,
+     Myriad,
+     LastVendorType = Myriad
+   };
+####
+--- include/llvm/ADT/SmallVector.h	2015-09-10 02:46:47.000000000 -0700
++++ include/llvm/ADT/SmallVector.h	2016-05-28 15:24:24.738410753 -0700
+@@ -19,6 +19,7 @@
+ #include "llvm/Support/Compiler.h"
+ #include "llvm/Support/MathExtras.h"
+ #include "llvm/Support/type_traits.h"
++
+ #include <algorithm>
+ #include <cassert>
+ #include <cstddef>
+@@ -27,6 +28,9 @@
+ #include <initializer_list>
+ #include <iterator>
+ #include <memory>
++#include <cstdio>
++#include <type_traits>
++#include <typeinfo>
+ 
+ namespace llvm {
+ 
+@@ -251,11 +255,27 @@
+ void SmallVectorTemplateBase<T, isPodLike>::grow(size_t MinSize) {
+   size_t CurCapacity = this->capacity();
+   size_t CurSize = this->size();
++
+   // Always grow, even from zero.
+   size_t NewCapacity = size_t(NextPowerOf2(CurCapacity+2));
+   if (NewCapacity < MinSize)
+     NewCapacity = MinSize;
++
++  NewCapacity = llvm::RoundUpToAlignment(NewCapacity,
++                                         llvm::alignOf<uint64_t>());
++
++#if defined(HAVE_POSIX_MEMALIGN)
++  T *NewElts;
++  size_t Alignment =
++    std::max<size_t>(llvm::AlignOf<uint64_t>::Alignment,
++                     llvm::AlignOf<T>::Alignment);
++  size_t Size = NewCapacity * sizeof(T);
++  int R = posix_memalign((void**) &NewElts, Alignment, Size);
++  assert((R == 0) && "posix_memalign failed!");
++  (void) std::memset(NewElts, 0, Size);
++#else
+   T *NewElts = static_cast<T*>(malloc(NewCapacity*sizeof(T)));
++#endif
+ 
+   // Move the elements over.
+   this->uninitialized_move(this->begin(), this->end(), NewElts);
+@@ -410,10 +430,44 @@
+       this->grow(N);
+   }
+ 
++  // This function is evil.
++  // Be very careful here with move vs. copy semantics.
+   T LLVM_ATTRIBUTE_UNUSED_RESULT pop_back_val() {
+-    T Result = ::std::move(this->back());
+-    this->pop_back();
+-    return Result;
++    if (std::is_move_constructible<T>::value &&
++        std::is_move_assignable<T>::value) {
++      T Result = std::move(this->back());
++      this->pop_back();
++      return Result;
++    } else if (std::is_copy_constructible<T>::value &&
++               std::is_copy_assignable<T>::value) {
++      T Result = this->back();
++      this->pop_back();
++      return Result;
++    }
++
++    // We can't use llvm::errs() because it has a circular
++    // dependency on llvm::SmallVector<T>.
++    if (!std::is_copy_constructible<T>::value) {
++      std::fprintf(stderr,
++                   "%s: Type %s is not copy-constructible!\n",
++                   __PRETTY_FUNCTION__, typeid(T).name());
++      abort();
++    } else if (!std::is_copy_assignable<T>::value) {
++      std::fprintf(stderr,
++                   "%s: Type %s is not copy-assignable!\n",
++                   __PRETTY_FUNCTION__, typeid(T).name());
++      abort();
++    } else if (!std::is_move_constructible<T>::value) {
++      std::fprintf(stderr,
++                   "%s: Type %s is not move-constructible!\n",
++                   __PRETTY_FUNCTION__, typeid(T).name());
++      abort();
++    } else if (!std::is_move_assignable<T>::value) {
++      std::fprintf(stderr,
++                   "%s: Type %s is not move-assignable!\n",
++                   __PRETTY_FUNCTION__, typeid(T).name());
++      abort();
++    }
+   }
+ 
+   void swap(SmallVectorImpl &RHS);
+###
+--- include/llvm/ADT/Twine.h	2016-01-10 00:27:13.000000000 -0800
++++ include/llvm/ADT/Twine.h	2016-07-16 22:13:18.628217595 -0700
+@@ -129,8 +129,7 @@
+       UHexKind
+     };
+ 
+-    union Child
+-    {
++    union Child {
+       const Twine *twine;
+       const char *cString;
+       const std::string *stdString;
+@@ -144,6 +143,7 @@
+       const unsigned long long *decULL;
+       const long long *decLL;
+       const uint64_t *uHex;
++      uint64_t buffer[1];
+     };
+ 
+   private:
+@@ -161,28 +161,32 @@
+   private:
+     /// Construct a nullary twine; the kind must be NullKind or EmptyKind.
+     explicit Twine(NodeKind Kind)
+-      : LHSKind(Kind), RHSKind(EmptyKind) {
++      : LHS(), RHS(), LHSKind(Kind), RHSKind(EmptyKind) {
+       assert(isNullary() && "Invalid kind!");
++      (void) memset(LHS.buffer, 0, sizeof(LHS.buffer));
++      (void) memset(RHS.buffer, 0, sizeof(RHS.buffer));
++      LHS.twine = 0L;
++      RHS.twine = 0L;
+     }
+ 
+     /// Construct a binary twine.
+-    explicit Twine(const Twine &LHS, const Twine &RHS)
+-        : LHSKind(TwineKind), RHSKind(TwineKind) {
+-      this->LHS.twine = &LHS;
+-      this->RHS.twine = &RHS;
+-      assert(isValid() && "Invalid twine!");
++    explicit Twine(const Twine &TLHS, const Twine &TRHS)
++      : LHSKind(TwineKind), RHSKind(TwineKind) {
++        (void) memset(LHS.buffer, 0, sizeof(LHS.buffer));
++        (void) memset(RHS.buffer, 0, sizeof(RHS.buffer));
++        this->LHS.twine = &TLHS;
++        this->RHS.twine = &TRHS;
++        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) {
++    explicit Twine(Child CLHS, NodeKind LHSKind, Child CRHS, NodeKind RHSKind)
++        : LHS(CLHS), RHS(CRHS), LHSKind(LHSKind), RHSKind(RHSKind) {
+       assert(isValid() && "Invalid twine!");
++      (void) memcpy(LHS.buffer, CLHS.buffer, sizeof(LHS.buffer));
++      (void) memcpy(RHS.buffer, CRHS.buffer, sizeof(RHS.buffer));
+     }
+ 
+-    /// Since the intended use of twines is as temporary objects, assignments
+-    /// when concatenating might cause undefined behavior or stack corruptions
+-    Twine &operator=(const Twine &Other) = delete;
+-
+     /// Check for the null twine.
+     bool isNull() const {
+       return getLHSKind() == NullKind;
+@@ -252,11 +256,25 @@
+     /// @{
+ 
+     /// Construct from an empty string.
+-    /*implicit*/ Twine() : LHSKind(EmptyKind), RHSKind(EmptyKind) {
++    /*implicit*/ Twine()
++    : LHS(), RHS(), LHSKind(EmptyKind), RHSKind(EmptyKind) {
++      (void) memset(LHS.buffer, 0, sizeof(LHS.buffer));
++      (void) memset(RHS.buffer, 0, sizeof(RHS.buffer));
++
+       assert(isValid() && "Invalid twine!");
+     }
+ 
+-    Twine(const Twine &) = default;
++    Twine(const Twine &RHST)
++    : LHS(), RHS(), LHSKind(RHST.LHSKind), RHSKind(RHST.RHSKind) {
++      (void) memcpy(LHS.buffer, RHST.LHS.buffer, sizeof(LHS.buffer));
++      (void) memcpy(RHS.buffer, RHST.RHS.buffer, sizeof(RHS.buffer));
++    }
++
++    Twine(Twine &&RHST)
++    : LHS(), RHS(), LHSKind(RHST.LHSKind), RHSKind(RHST.RHSKind) {
++      (void) memcpy(LHS.buffer, RHST.LHS.buffer, sizeof(LHS.buffer));
++      (void) memcpy(RHS.buffer, RHST.RHS.buffer, sizeof(RHS.buffer));
++    }
+ 
+     /// Construct from a C string.
+     ///
+@@ -264,7 +282,10 @@
+     /// optimized out for string constants. This allows Twine arguments have
+     /// default "" values, without introducing unnecessary string constants.
+     /*implicit*/ Twine(const char *Str)
+-      : RHSKind(EmptyKind) {
++      : LHS(), RHS(), LHSKind(EmptyKind), RHSKind(EmptyKind) {
++      (void) memset(LHS.buffer, 0, sizeof(LHS.buffer));
++      (void) memset(RHS.buffer, 0, sizeof(RHS.buffer));
++
+       if (Str[0] != '\0') {
+         LHS.cString = Str;
+         LHSKind = CStringKind;
+@@ -276,76 +297,113 @@
+ 
+     /// Construct from an std::string.
+     /*implicit*/ Twine(const std::string &Str)
+-      : LHSKind(StdStringKind), RHSKind(EmptyKind) {
++      : LHS(), RHS(), LHSKind(StdStringKind), RHSKind(EmptyKind) {
++      (void) memset(LHS.buffer, 0, sizeof(LHS.buffer));
++      (void) memset(RHS.buffer, 0, sizeof(RHS.buffer));
++
+       LHS.stdString = &Str;
+       assert(isValid() && "Invalid twine!");
+     }
+ 
+     /// Construct from a StringRef.
+     /*implicit*/ Twine(const StringRef &Str)
+-      : LHSKind(StringRefKind), RHSKind(EmptyKind) {
++      : LHS(), RHS(), LHSKind(StringRefKind), RHSKind(EmptyKind) {
++      (void) memset(LHS.buffer, 0, sizeof(LHS.buffer));
++      (void) memset(RHS.buffer, 0, sizeof(RHS.buffer));
++
+       LHS.stringRef = &Str;
+       assert(isValid() && "Invalid twine!");
+     }
+ 
+     /// Construct from a SmallString.
+     /*implicit*/ Twine(const SmallVectorImpl<char> &Str)
+-      : LHSKind(SmallStringKind), RHSKind(EmptyKind) {
++      : LHS(), RHS(), LHSKind(SmallStringKind), RHSKind(EmptyKind) {
++      (void) memset(LHS.buffer, 0, sizeof(LHS.buffer));
++      (void) memset(RHS.buffer, 0, sizeof(RHS.buffer));
++
+       LHS.smallString = &Str;
+       assert(isValid() && "Invalid twine!");
+     }
+ 
+     /// Construct from a char.
+     explicit Twine(char Val)
+-      : LHSKind(CharKind), RHSKind(EmptyKind) {
++      : LHS(), RHS(), LHSKind(CharKind), RHSKind(EmptyKind) {
++      (void) memset(LHS.buffer, 0, sizeof(LHS.buffer));
++      (void) memset(RHS.buffer, 0, sizeof(RHS.buffer));
++
+       LHS.character = Val;
+     }
+ 
+     /// Construct from a signed char.
+     explicit Twine(signed char Val)
+-      : LHSKind(CharKind), RHSKind(EmptyKind) {
++      : LHS(), RHS(), LHSKind(CharKind), RHSKind(EmptyKind) {
++      (void) memset(LHS.buffer, 0, sizeof(LHS.buffer));
++      (void) memset(RHS.buffer, 0, sizeof(RHS.buffer));
++
++      LHS.character = Val;
+       LHS.character = static_cast<char>(Val);
+     }
+ 
+     /// Construct from an unsigned char.
+     explicit Twine(unsigned char Val)
+-      : LHSKind(CharKind), RHSKind(EmptyKind) {
++      : LHS(), RHS(), LHSKind(CharKind), RHSKind(EmptyKind) {
++      (void) memset(LHS.buffer, 0, sizeof(LHS.buffer));
++      (void) memset(RHS.buffer, 0, sizeof(RHS.buffer));
++
+       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(), RHS(), LHSKind(DecUIKind), RHSKind(EmptyKind) {
++      (void) memset(LHS.buffer, 0, sizeof(LHS.buffer));
++      (void) memset(RHS.buffer, 0, sizeof(RHS.buffer));
++
+       LHS.decUI = Val;
+     }
+ 
+     /// Construct a twine to print \p Val as a signed decimal integer.
+     explicit Twine(int Val)
+-      : LHSKind(DecIKind), RHSKind(EmptyKind) {
++      : LHS(), RHS(), LHSKind(DecIKind), RHSKind(EmptyKind) {
++      (void) memset(LHS.buffer, 0, sizeof(LHS.buffer));
++      (void) memset(RHS.buffer, 0, sizeof(RHS.buffer));
++
+       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(), RHS(), LHSKind(DecULKind), RHSKind(EmptyKind) {
++      (void) memset(LHS.buffer, 0, sizeof(LHS.buffer));
++      (void) memset(RHS.buffer, 0, sizeof(RHS.buffer));
++
+       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(), RHS(), LHSKind(DecLKind), RHSKind(EmptyKind) {
++      (void) memset(LHS.buffer, 0, sizeof(LHS.buffer));
++      (void) memset(RHS.buffer, 0, sizeof(RHS.buffer));
++
+       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(), RHS(), LHSKind(DecULLKind), RHSKind(EmptyKind) {
++      (void) memset(LHS.buffer, 0, sizeof(LHS.buffer));
++      (void) memset(RHS.buffer, 0, sizeof(RHS.buffer));
++
+       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(), RHS(), LHSKind(DecLLKind), RHSKind(EmptyKind) {
++      (void) memset(LHS.buffer, 0, sizeof(LHS.buffer));
++      (void) memset(RHS.buffer, 0, sizeof(RHS.buffer));
++
+       LHS.decLL = &Val;
+     }
+ 
+@@ -355,27 +413,62 @@
+     // 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) {
+-      this->LHS.cString = LHS;
+-      this->RHS.stringRef = &RHS;
++    /*implicit*/ explicit Twine(const char *CLHS, const StringRef &SRHS)
++        : LHS(), RHS(), LHSKind(CStringKind), RHSKind(StringRefKind) {
++      (void) memset(LHS.buffer, 0, sizeof(LHS.buffer));
++      (void) memset(RHS.buffer, 0, sizeof(RHS.buffer));
++
++      this->LHS.cString = CLHS;
++      this->RHS.stringRef = &SRHS;
+       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) {
+-      this->LHS.stringRef = &LHS;
+-      this->RHS.cString = RHS;
++    /*implicit*/ explicit Twine(const StringRef &SLHS, const char *CRHS)
++        : LHS(), RHS(), LHSKind(StringRefKind), RHSKind(CStringKind) {
++      (void) memset(LHS.buffer, 0, sizeof(LHS.buffer));
++      (void) memset(RHS.buffer, 0, sizeof(RHS.buffer));
++
++      this->LHS.stringRef = &SLHS;
++      this->RHS.cString = CRHS;
+       assert(isValid() && "Invalid twine!");
+     }
+ 
++    /// Assignment operators.
++    Twine &operator=(const Twine &TRHS) {
++      if (this != &TRHS) {
++        (void) memset(LHS.buffer, 0, sizeof(LHS.buffer));
++        (void) memset(RHS.buffer, 0, sizeof(RHS.buffer));
++        (void) memcpy(LHS.buffer, TRHS.LHS.buffer, sizeof(LHS.buffer));
++        (void) memcpy(RHS.buffer, TRHS.RHS.buffer, sizeof(RHS.buffer));
++      }
++
++      return *this;
++    }
++
++    const Twine &operator=(Twine &&TRHS) {
++      if (this != &TRHS) {
++        (void) memset(LHS.buffer, 0, sizeof(LHS.buffer));
++        (void) memset(RHS.buffer, 0, sizeof(RHS.buffer));
++        (void) memcpy(LHS.buffer, TRHS.LHS.buffer, sizeof(LHS.buffer));
++        (void) memcpy(RHS.buffer, TRHS.RHS.buffer, sizeof(RHS.buffer));
++      }
++
++      return *this;
++    }
++
+     /// Create a 'null' string, which is an empty string that always
+     /// concatenates to form another empty string.
+     static Twine createNull() {
+       return Twine(NullKind);
+     }
+ 
++    /// Create an empty string, which is an empty string that always
++    /// concatenates to form another empty string.
++    static Twine createEmpty() {
++      return Twine(EmptyKind);
++    }
++
+     /// @}
+     /// @name Numeric Conversions
+     /// @{
--- a/components/llvm/patches/004-configure.ac.patch	Thu Jul 28 16:15:45 2016 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,27 +0,0 @@
-# Solaris autoconf-based build.
-# https://llvm.org/bugs/show_bug.cgi?id=24641
---- autoconf/configure.ac	2015-05-01 21:17:33.000000000 -0700
-+++ autoconf/configure.ac	2015-06-01 09:30:27.734038335 -0700
-@@ -1486,8 +1486,11 @@
- fi
- 
- dnl mallinfo is optional; the code can compile (minus features) without it
-+dnl Explicitly disable on Solaris.
-+if test "$llvm_cv_target_os_type" != "SunOS" ; then
- AC_SEARCH_LIBS(mallinfo,malloc,AC_DEFINE([HAVE_MALLINFO],[1],
-                [Define if mallinfo() is available on this platform.]))
-+fi
- 
- dnl pthread locking functions are optional - but llvm will not be thread-safe
- dnl without locks.
-@@ -1965,7 +1968,10 @@
- fi
- 
- dnl Determine whether the compiler supports -fvisibility-inlines-hidden.
-+dnl Explicitly disable on Solaris.
-+if test "$llvm_cv_target_os_type" != "SunOS" ; then
- AC_CXX_USE_VISIBILITY_INLINES_HIDDEN
-+fi
- 
- dnl Determine linker rpath flag
- if test "$llvm_cv_link_use_r" = "yes" ; then
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/004-solaris-LLVM-libIR.patch	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,1048 @@
+# 22902339 memory corruption caused by undefined behavior in LLVM IR Module
+# 24314687 static initialization of optimization passes doesn't work as
+# intended
+# 3.9.X for upstream.
+--- include/llvm/IR/BasicBlock.h	2015-11-10 18:26:42.000000000 -0800
++++ include/llvm/IR/BasicBlock.h	2016-05-28 16:37:28.925076023 -0700
+@@ -78,10 +78,11 @@
+   LLVMContext &getContext() const;
+ 
+   /// Instruction iterators...
+-  typedef InstListType::iterator iterator;
+-  typedef InstListType::const_iterator const_iterator;
+-  typedef InstListType::reverse_iterator reverse_iterator;
+-  typedef InstListType::const_reverse_iterator const_reverse_iterator;
++  typedef SymbolTableList<Instruction>::iterator iterator;
++  typedef SymbolTableList<Instruction>::const_iterator const_iterator;
++  typedef SymbolTableList<Instruction>::reverse_iterator reverse_iterator;
++  typedef SymbolTableList<Instruction>::const_reverse_iterator
++          const_reverse_iterator;
+ 
+   /// \brief Creates a new BasicBlock.
+   ///
+@@ -148,8 +149,8 @@
+   /// suitable for inserting a non-PHI instruction.
+   ///
+   /// In particular, it skips all PHIs and LandingPad instructions.
+-  iterator getFirstInsertionPt();
+-  const_iterator getFirstInsertionPt() const {
++  BasicBlock::iterator getFirstInsertionPt();
++  BasicBlock::const_iterator getFirstInsertionPt() const {
+     return const_cast<BasicBlock*>(this)->getFirstInsertionPt();
+   }
+ 
+###
+--- include/llvm/IR/Value.h	2016-02-04 08:59:45.000000000 -0800
++++ include/llvm/IR/Value.h	2016-05-29 12:21:18.779271419 -0700
+@@ -74,6 +74,7 @@
+ 
+   const unsigned char SubclassID;   // Subclass identifier (for isa/dyn_cast)
+   unsigned char HasValueHandle : 1; // Has a ValueHandle pointing to this?
++
+ protected:
+   /// \brief Hold subclass data that can be dropped.
+   ///
+@@ -113,17 +114,25 @@
+ 
+ private:
+   template <typename UseT> // UseT == 'Use' or 'const Use'
+-  class use_iterator_impl
+-      : public std::iterator<std::forward_iterator_tag, UseT *> {
++  class use_iterator_impl :
++    public std::iterator<std::forward_iterator_tag, UseT *> {
+     UseT *U;
+-    explicit use_iterator_impl(UseT *u) : U(u) {}
++
++    explicit use_iterator_impl(UseT *u)
++      : std::iterator<std::forward_iterator_tag, UseT *>(), U(u) { }
+     friend class Value;
+ 
+   public:
+-    use_iterator_impl() : U() {}
++    use_iterator_impl()
++      : std::iterator<std::forward_iterator_tag, UseT *>(), U(nullptr) { }
+ 
+-    bool operator==(const use_iterator_impl &x) const { return U == x.U; }
+-    bool operator!=(const use_iterator_impl &x) const { return !operator==(x); }
++    bool operator==(const use_iterator_impl &x) const {
++      return U == x.U;
++    }
++
++    bool operator!=(const use_iterator_impl &x) const {
++      return !operator==(x);
++    }
+ 
+     use_iterator_impl &operator++() { // Preincrement
+       assert(U && "Cannot increment end iterator!");
+@@ -150,18 +159,28 @@
+ 
+   template <typename UserTy> // UserTy == 'User' or 'const User'
+   class user_iterator_impl
+-      : public std::iterator<std::forward_iterator_tag, UserTy *> {
++  : public std::iterator<std::forward_iterator_tag, UserTy *> {
++  private:
+     use_iterator_impl<Use> UI;
+-    explicit user_iterator_impl(Use *U) : UI(U) {}
++
++    explicit user_iterator_impl(Use *U)
++      : std::iterator<std::forward_iterator_tag, UserTy *>(), UI(U) { }
+     friend class Value;
+ 
+   public:
+-    user_iterator_impl() {}
++    user_iterator_impl()
++    : std::iterator<std::forward_iterator_tag, UserTy *>(), UI() { }
+ 
+-    bool operator==(const user_iterator_impl &x) const { return UI == x.UI; }
+-    bool operator!=(const user_iterator_impl &x) const { return !operator==(x); }
++    bool operator==(const user_iterator_impl &x) const {
++      return UI == x.UI;
++    }
+ 
+-    /// \brief Returns true if this iterator is equal to user_end() on the value.
++    bool operator!=(const user_iterator_impl &x) const {
++      return !operator==(x);
++    }
++
++    /// \brief Returns true if this iterator is equal to user_end()
++    /// on the value.
+     bool atEnd() const { return *this == user_iterator_impl(); }
+ 
+     user_iterator_impl &operator++() { // Preincrement
+@@ -193,6 +212,7 @@
+ 
+ protected:
+   Value(Type *Ty, unsigned scid);
++
+ public:
+   virtual ~Value();
+ 
+###
+--- lib/IR/User.cpp	2015-09-23 18:00:49.000000000 -0700
++++ lib/IR/User.cpp	2016-05-29 12:13:16.188732011 -0700
+@@ -12,6 +12,8 @@
+ #include "llvm/IR/GlobalValue.h"
+ #include "llvm/IR/Operator.h"
+ 
++#include <cstdlib>
++
+ namespace llvm {
+ class BasicBlock;
+ 
+@@ -42,33 +44,53 @@
+ 
+ void User::allocHungoffUses(unsigned N, bool IsPhi) {
+   assert(HasHungOffUses && "alloc must have hung off uses");
+-
+-  static_assert(AlignOf<Use>::Alignment >= AlignOf<Use::UserRef>::Alignment,
+-                "Alignment is insufficient for 'hung-off-uses' pieces");
++  static_assert(AlignOf<Use>::Alignment >=
++                AlignOf<Use::UserRef>::Alignment,
++                "Insufficient alignment for 'hung-off-uses' pieces");
+   static_assert(AlignOf<Use::UserRef>::Alignment >=
+-                    AlignOf<BasicBlock *>::Alignment,
+-                "Alignment is insufficient for 'hung-off-uses' pieces");
++                AlignOf<BasicBlock*>::Alignment,
++                "Insufficient alignment for 'hung-off-uses' pieces");
+ 
+   // Allocate the array of Uses, followed by a pointer (with bottom bit set) to
+   // the User.
+   size_t size = N * sizeof(Use) + sizeof(Use::UserRef);
+   if (IsPhi)
+     size += N * sizeof(BasicBlock *);
+-  Use *Begin = static_cast<Use*>(::operator new(size));
++
++  size_t Alignment =
++    std::max<size_t>(AlignOf<Use>::Alignment,
++                     std::max<size_t>(AlignOf<BasicBlock*>::Alignment,
++                                      AlignOf<Use::UserRef>::Alignment));
++  size = llvm::RoundUpToAlignment(size, Alignment);
++  void *Mem;
++
++  if (posix_memalign(&Mem, Alignment, size) != 0) {
++    llvm::errs() << __PRETTY_FUNCTION__
++      << ": posix_memalign(3c) failed!\n";
++    abort();
++  }
++
++  (void) std::memset(Mem, 0, size);
++  Use *Begin = reinterpret_cast<Use*>(Mem);
+   Use *End = Begin + N;
+   (void) new(End) Use::UserRef(const_cast<User*>(this), 1);
+   setOperandList(Use::initTags(Begin, End));
+ }
+ 
+ void User::growHungoffUses(unsigned NewNumUses, bool IsPhi) {
+-  assert(HasHungOffUses && "realloc must have hung off uses");
+-
++  assert(HasHungOffUses && "alloc must have hung off uses");
+   unsigned OldNumUses = getNumOperands();
+ 
+   // We don't support shrinking the number of uses.  We wouldn't have enough
+   // space to copy the old uses in to the new space.
+   assert(NewNumUses > OldNumUses && "realloc must grow num uses");
+ 
++  if (OldNumUses >= NewNumUses) {
++    llvm::errs() << __PRETTY_FUNCTION__
++      << ": reallocation must grow new uses!\n";
++    abort();
++  }
++
+   Use *OldOps = getOperandList();
+   allocHungoffUses(NewNumUses, IsPhi);
+   Use *NewOps = getOperandList();
+@@ -101,7 +123,6 @@
+ 
+ MutableArrayRef<uint8_t> User::getDescriptor() {
+   assert(HasDescriptor && "Don't call otherwise!");
+-  assert(!HasHungOffUses && "Invariant!");
+ 
+   auto *DI = reinterpret_cast<DescriptorInfo *>(getIntrusiveOperands()) - 1;
+   assert(DI->SizeInBytes != 0 && "Should not have had a descriptor otherwise!");
+@@ -114,20 +135,31 @@
+ //                         User operator new Implementations
+ //===----------------------------------------------------------------------===//
+ 
+-void *User::allocateFixedOperandUser(size_t Size, unsigned Us,
+-                                     unsigned DescBytes) {
++void* LLVM_ATTRIBUTE_NOINLINE
++User::allocateFixedOperandUser(size_t Size, unsigned Us, unsigned DescBytes) {
+   assert(Us < (1u << NumUserOperandsBits) && "Too many operands");
+ 
+   static_assert(sizeof(DescriptorInfo) % sizeof(void *) == 0, "Required below");
+ 
+   unsigned DescBytesToAllocate =
+-      DescBytes == 0 ? 0 : (DescBytes + sizeof(DescriptorInfo));
++    DescBytes == 0 ?  0 : (DescBytes + sizeof(DescriptorInfo));
++  DescBytesToAllocate = llvm::RoundUpToAlignment(DescBytesToAllocate, 8U);
+   assert(DescBytesToAllocate % sizeof(void *) == 0 &&
+          "We need this to satisfy alignment constraints for Uses");
+ 
+-  uint8_t *Storage = static_cast<uint8_t *>(
+-      ::operator new(Size + sizeof(Use) * Us + DescBytesToAllocate));
+-  Use *Start = reinterpret_cast<Use *>(Storage + DescBytesToAllocate);
++  unsigned AllocSize = Size + sizeof(Use) * Us + DescBytesToAllocate;
++  AllocSize = std::max<unsigned>(AllocSize, alignof(void*));
++
++  uint8_t *Storage;
++  if (posix_memalign(reinterpret_cast<void**>(&Storage),
++                     llvm::AlignOf<uint64_t>::Alignment, AllocSize) != 0) {
++    llvm::errs() << __PRETTY_FUNCTION__
++      << ": posix_memalign(3c) failed!\n";
++    abort();
++  }
++
++  Use *Start = reinterpret_cast<Use*>(reinterpret_cast<void*>(
++      reinterpret_cast<uint8_t*>(Storage) + DescBytesToAllocate));
+   Use *End = Start + Us;
+   User *Obj = reinterpret_cast<User*>(End);
+   Obj->NumUserOperands = Us;
+@@ -153,7 +185,16 @@
+ 
+ void *User::operator new(size_t Size) {
+   // Allocate space for a single Use*
+-  void *Storage = ::operator new(Size + sizeof(Use *));
++  void *Storage;
++  unsigned AllocSize = Size + sizeof(Use*);
++  AllocSize = std::max<unsigned>(AllocSize, sizeof(void*));
++  if (posix_memalign(&Storage, llvm::AlignOf<uint64_t>::Alignment,
++                     AllocSize) != 0) {
++    llvm::errs() << __PRETTY_FUNCTION__
++      << ": posix_memalign(3c) failed!\n";
++    abort();
++  }
++
+   Use **HungOffOperandList = static_cast<Use **>(Storage);
+   User *Obj = reinterpret_cast<User *>(HungOffOperandList + 1);
+   Obj->NumUserOperands = 0;
+@@ -170,7 +211,7 @@
+ void User::operator delete(void *Usr) {
+   // Hung off uses use a single Use* before the User, while other subclasses
+   // use a Use[] allocated prior to the user.
+-  User *Obj = static_cast<User *>(Usr);
++  User *Obj = reinterpret_cast<User *>(Usr);
+   if (Obj->HasHungOffUses) {
+     assert(!Obj->HasDescriptor && "not supported!");
+ 
+@@ -178,19 +219,19 @@
+     // drop the hung off uses.
+     Use::zap(*HungOffOperandList, *HungOffOperandList + Obj->NumUserOperands,
+              /* Delete */ true);
+-    ::operator delete(HungOffOperandList);
++    std::free(reinterpret_cast<void*>(HungOffOperandList));
+   } else if (Obj->HasDescriptor) {
+     Use *UseBegin = static_cast<Use *>(Usr) - Obj->NumUserOperands;
+     Use::zap(UseBegin, UseBegin + Obj->NumUserOperands, /* Delete */ false);
+ 
+     auto *DI = reinterpret_cast<DescriptorInfo *>(UseBegin) - 1;
+-    uint8_t *Storage = reinterpret_cast<uint8_t *>(DI) - DI->SizeInBytes;
+-    ::operator delete(Storage);
++    uint64_t *Storage = reinterpret_cast<uint64_t *>(DI) - DI->SizeInBytes;
++    std::free(reinterpret_cast<void*>(Storage));
+   } else {
+-    Use *Storage = static_cast<Use *>(Usr) - Obj->NumUserOperands;
++    Use *Storage = reinterpret_cast<Use *>(Usr) - Obj->NumUserOperands;
+     Use::zap(Storage, Storage + Obj->NumUserOperands,
+              /* Delete */ false);
+-    ::operator delete(Storage);
++    std::free(reinterpret_cast<void*>(Storage));
+   }
+ }
+ 
+###
+--- include/llvm/IR/User.h	2015-12-18 23:52:49.000000000 -0900
++++ include/llvm/IR/User.h	2016-07-06 18:49:29.963198410 -0800
+@@ -40,7 +40,7 @@
+   friend struct HungoffOperandTraits;
+   virtual void anchor();
+ 
+-  LLVM_ATTRIBUTE_ALWAYS_INLINE inline static void *
++  static void* LLVM_ATTRIBUTE_NOINLINE
+   allocateFixedOperandUser(size_t, unsigned, unsigned);
+ 
+ protected:
+###
+--- include/llvm/IR/Attributes.h	2015-12-22 18:57:37.000000000 -0500
++++ include/llvm/IR/Attributes.h	2016-05-08 23:19:20.515430339 -0400
+@@ -399,20 +399,25 @@
+ 
+ public:
+   AttrBuilder()
+-      : Attrs(0), Alignment(0), StackAlignment(0), DerefBytes(0),
+-        DerefOrNullBytes(0) {}
++    : Attrs(0), TargetDepAttrs(), Alignment(0), StackAlignment(0),
++  DerefBytes(0), DerefOrNullBytes(0) { }
++
+   explicit AttrBuilder(uint64_t Val)
+-      : Attrs(0), Alignment(0), StackAlignment(0), DerefBytes(0),
+-        DerefOrNullBytes(0) {
++    : Attrs(0), TargetDepAttrs(), Alignment(0), StackAlignment(0),
++    DerefBytes(0), DerefOrNullBytes(0) {
+     addRawValue(Val);
+   }
++
+   AttrBuilder(const Attribute &A)
+-      : Attrs(0), Alignment(0), StackAlignment(0), DerefBytes(0),
+-        DerefOrNullBytes(0) {
++    : Attrs(0), TargetDepAttrs(), Alignment(0), StackAlignment(0),
++    DerefBytes(0), DerefOrNullBytes(0) {
+     addAttribute(A);
+   }
++
+   AttrBuilder(AttributeSet AS, unsigned Idx);
+ 
++  ~AttrBuilder() { }
++
+   void clear();
+ 
+   /// \brief Add an attribute to the builder.
+###
+--- include/llvm/IR/IRBuilder.h	2016-02-18 16:08:56.000000000 -0800
++++ include/llvm/IR/IRBuilder.h	2016-05-09 19:14:26.534949228 -0700
+@@ -64,13 +64,15 @@
+   ArrayRef<OperandBundleDef> DefaultOperandBundles;
+ 
+ public:
+-  IRBuilderBase(LLVMContext &context, MDNode *FPMathTag = nullptr,
++  IRBuilderBase(LLVMContext &Ctx, MDNode *FPMathTag = nullptr,
+                 ArrayRef<OperandBundleDef> OpBundles = None)
+-      : Context(context), DefaultFPMathTag(FPMathTag), FMF(),
+-        DefaultOperandBundles(OpBundles) {
+-    ClearInsertionPoint();
++  : CurDbgLocation(), BB(nullptr), InsertPt(), Context(Ctx),
++  DefaultFPMathTag(FPMathTag), FMF(), DefaultOperandBundles(OpBundles) {
++    InsertPt.reset(nullptr);
+   }
+ 
++  virtual ~IRBuilderBase() { }
++
+   //===--------------------------------------------------------------------===//
+   // Builder configuration methods
+   //===--------------------------------------------------------------------===//
+###
+--- lib/IR/IRBuilder.cpp	2015-11-18 21:56:52.000000000 -0800
++++ lib/IR/IRBuilder.cpp	2016-05-13 17:40:40.999056490 -0700
+@@ -18,8 +18,15 @@
+ #include "llvm/IR/Intrinsics.h"
+ #include "llvm/IR/LLVMContext.h"
+ #include "llvm/IR/Statepoint.h"
++#include "llvm/LinkAllIR.h"
+ using namespace llvm;
+ 
++namespace llvm {
++  /// See the file ${top_srcdir}/include/llvm/LinkAllIR.h for the
++  /// explanation for this hack.
++  ForceVMCoreLinking *ForceVMCoreLinking::FVMCL = new ForceVMCoreLinking();
++}
++
+ /// CreateGlobalString - Make a new global variable with an initializer that
+ /// has array of i8 type filled in with the nul terminated string value
+ /// specified.  If Name is specified, it is the name of the global variable
+###
+--- lib/IR/Verifier.cpp	2016-01-12 18:31:14.000000000 -0800
++++ lib/IR/Verifier.cpp	2016-05-14 07:42:08.348333940 -0700
+@@ -578,8 +578,12 @@
+ void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
+                                    const GlobalAlias &GA, const Constant &C) {
+   if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
++#if 0
++    // Check the DeclarationForLinker() for all the extern symbol references.
++    // This should not happen here in any scenario.
+     Assert(!GV->isDeclarationForLinker(), "Alias must point to a definition",
+            &GA);
++#endif
+ 
+     if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
+       Assert(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA);
+###
+--- include/llvm/IR/Metadata.h	2016-01-11 13:37:41.000000000 -0800
++++ include/llvm/IR/Metadata.h	2016-05-10 07:11:35.580234020 -0700
+@@ -25,6 +25,7 @@
+ #include "llvm/IR/LLVMContext.h"
+ #include "llvm/IR/Value.h"
+ #include "llvm/Support/ErrorHandling.h"
++#include "llvm/Support/raw_ostream.h"
+ #include <type_traits>
+ 
+ namespace llvm {
+@@ -42,6 +43,7 @@
+ /// This is a root class for typeless data in the IR.
+ class Metadata {
+   friend class ReplaceableMetadataImpl;
++  friend class MDNode;
+ 
+   /// \brief RTTI.
+   const unsigned char SubclassID;
+@@ -51,7 +53,8 @@
+   enum StorageType { Uniqued, Distinct, Temporary };
+ 
+   /// \brief Storage flag for non-uniqued, otherwise unowned, metadata.
+-  unsigned Storage : 2;
++  unsigned Storage;
++
+   // TODO: expose remaining bits to subclasses.
+ 
+   unsigned short SubclassData16;
+@@ -91,8 +94,9 @@
+ 
+ protected:
+   Metadata(unsigned ID, StorageType Storage)
+-      : SubclassID(ID), Storage(Storage), SubclassData16(0), SubclassData32(0) {
+-  }
++    : SubclassID(ID), Storage(Storage), SubclassData16(0),
++    SubclassData32(0) { }
++
+   ~Metadata() = default;
+ 
+   /// \brief Default handling of a changed operand, which asserts.
+@@ -283,13 +287,15 @@
+   LLVMContext &Context;
+   uint64_t NextIndex;
+   SmallDenseMap<void *, std::pair<OwnerTy, uint64_t>, 4> UseMap;
++
+   /// Flag that can be set to false if this metadata should not be
+   /// RAUW'ed, e.g. if it is used as the key of a map.
+   bool CanReplace;
+ 
+ public:
+-  ReplaceableMetadataImpl(LLVMContext &Context)
+-      : Context(Context), NextIndex(0), CanReplace(true) {}
++  ReplaceableMetadataImpl(LLVMContext &Ctx)
++    : Context(Ctx), NextIndex(0), UseMap(), CanReplace(true) { }
++
+   ~ReplaceableMetadataImpl() {
+     assert(UseMap.empty() && "Cannot destroy in-use replaceable metadata");
+   }
+@@ -327,7 +333,7 @@
+ /// Because of full uniquing support, each value is only wrapped by a single \a
+ /// ValueAsMetadata object, so the lookup maps are far more efficient than
+ /// those using ValueHandleBase.
+-class ValueAsMetadata : public Metadata, ReplaceableMetadataImpl {
++class ValueAsMetadata : public Metadata, public ReplaceableMetadataImpl {
+   friend class ReplaceableMetadataImpl;
+   friend class LLVMContextImpl;
+ 
+@@ -343,6 +349,7 @@
+       : Metadata(ID, Uniqued), ReplaceableMetadataImpl(V->getContext()), V(V) {
+     assert(V && "Expected valid value");
+   }
++
+   ~ValueAsMetadata() = default;
+ 
+ public:
+@@ -396,6 +403,7 @@
+   static ConstantAsMetadata *get(Constant *C) {
+     return ValueAsMetadata::getConstant(C);
+   }
++
+   static ConstantAsMetadata *getIfExists(Constant *C) {
+     return ValueAsMetadata::getConstantIfExists(C);
+   }
+@@ -421,6 +429,7 @@
+   static LocalAsMetadata *get(Value *Local) {
+     return ValueAsMetadata::getLocal(Local);
+   }
++
+   static LocalAsMetadata *getIfExists(Value *Local) {
+     return ValueAsMetadata::getLocalIfExists(Local);
+   }
+@@ -748,6 +757,7 @@
+       : Ptr(ReplaceableUses.release()) {
+     assert(getReplaceableUses() && "Expected non-null replaceable uses");
+   }
++
+   ~ContextAndReplaceableUses() { delete getReplaceableUses(); }
+ 
+   operator LLVMContext &() { return getContext(); }
+@@ -756,11 +766,13 @@
+   bool hasReplaceableUses() const {
+     return Ptr.is<ReplaceableMetadataImpl *>();
+   }
++
+   LLVMContext &getContext() const {
+     if (hasReplaceableUses())
+       return getReplaceableUses()->getContext();
+     return *Ptr.get<LLVMContext *>();
+   }
++
+   ReplaceableMetadataImpl *getReplaceableUses() const {
+     if (hasReplaceableUses())
+       return Ptr.get<ReplaceableMetadataImpl *>();
+@@ -820,10 +832,11 @@
+ class MDNode : public Metadata {
+   friend class ReplaceableMetadataImpl;
+   friend class LLVMContextImpl;
++  friend class MDNodeFwdDecl;
++  friend class MDTuple;
+ 
+   MDNode(const MDNode &) = delete;
+   void operator=(const MDNode &) = delete;
+-  void *operator new(size_t) = delete;
+ 
+   unsigned NumOperands;
+   unsigned NumUnresolved;
+@@ -831,17 +844,21 @@
+ protected:
+   ContextAndReplaceableUses Context;
+ 
+-  void *operator new(size_t Size, unsigned NumOps);
+-  void operator delete(void *Mem);
++  static void *operator new(size_t Size, unsigned NumOps) throw();
++  static void operator delete(void *Mem) throw();
+ 
+   /// \brief Required by std, but never called.
+-  void operator delete(void *, unsigned) {
+-    llvm_unreachable("Constructor throws?");
++  static void operator delete(void *, unsigned) {
++    llvm::errs() << __PRETTY_FUNCTION__
++      << ": This should never be called!\n";
++    abort();
+   }
+ 
+   /// \brief Required by std, but never called.
+-  void operator delete(void *, unsigned, bool) {
+-    llvm_unreachable("Constructor throws?");
++  static void operator delete(void *, unsigned, bool) {
++    llvm::errs() << __PRETTY_FUNCTION__
++      << ": This should never be called!\n";
++    abort();
+   }
+ 
+   MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
+@@ -1082,6 +1099,7 @@
+       : MDNode(C, MDTupleKind, Storage, Vals) {
+     setHash(Hash);
+   }
++
+   ~MDTuple() { dropAllReferences(); }
+ 
+   void setHash(unsigned Hash) { SubclassData32 = Hash; }
+@@ -1096,12 +1114,16 @@
+   }
+ 
+ public:
++  void *operator new(size_t Size, unsigned NumOps) throw();
++  void operator delete(void *Mem) throw();
++
+   /// \brief Get the hash, if any.
+   unsigned getHash() const { return SubclassData32; }
+ 
+   static MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
+     return getImpl(Context, MDs, Uniqued);
+   }
++
+   static MDTuple *getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
+     return getImpl(Context, MDs, Uniqued, /* ShouldCreate */ false);
+   }
+@@ -1154,18 +1176,20 @@
+ /// An iterator that transforms an \a MDNode::iterator into an iterator over a
+ /// particular Metadata subclass.
+ template <class T>
+-class TypedMDOperandIterator
+-    : std::iterator<std::input_iterator_tag, T *, std::ptrdiff_t, void, T *> {
++class TypedMDOperandIterator : public std::iterator<std::input_iterator_tag, T *, std::ptrdiff_t, void, T *> {
++private:
+   MDNode::op_iterator I = nullptr;
+ 
+ public:
+   TypedMDOperandIterator() = default;
+   explicit TypedMDOperandIterator(MDNode::op_iterator I) : I(I) {}
+   T *operator*() const { return cast_or_null<T>(*I); }
++
+   TypedMDOperandIterator &operator++() {
+     ++I;
+     return *this;
+   }
++
+   TypedMDOperandIterator operator++(int) {
+     TypedMDOperandIterator Temp(*this);
+     ++I;
+@@ -1180,6 +1204,7 @@
+ /// This is a wrapper for \a MDTuple that makes it act like an array holding a
+ /// particular type of metadata.
+ template <class T> class MDTupleTypedArrayWrapper {
++private:
+   const MDTuple *N = nullptr;
+ 
+ public:
+###
+--- include/llvm/LinkAllIR.h	2014-01-13 01:26:24.000000000 -0800
++++ include/llvm/LinkAllIR.h	2016-07-06 07:55:18.900250515 -0800
+@@ -32,22 +32,49 @@
+ #include "llvm/Support/Program.h"
+ #include "llvm/Support/Signals.h"
+ #include "llvm/Support/TimeValue.h"
++
+ #include <cstdlib>
+ 
+-namespace {
+-  struct ForceVMCoreLinking {
++namespace llvm {
++  class ForceVMCoreLinking {
++  private:
+     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.
++      // Except for the fact that your theory doesn't work.
+       if (std::getenv("bar") != (char*) -1)
+         return;
+-      (void)new llvm::Module("", llvm::getGlobalContext());
+-      (void)new llvm::UnreachableInst(llvm::getGlobalContext());
+-      (void)    llvm::createVerifierPass(); 
++
++      // Hi, GCC. Please don't throw this function away.
++      asm("");
++
++      llvm::Module *M = new llvm::Module("", llvm::getGlobalContext());
++      (void) M;
++
++      llvm::Instruction *I =
++        new llvm::UnreachableInst(llvm::getGlobalContext());
++      (void) I;
++
++      FunctionPass *FP = llvm::createVerifierPass();
++      (void) FP;
+     }
+-  } ForceVMCoreLinking;
++
++  public:
++
++    static ForceVMCoreLinking *Initialize();
++
++    ~ForceVMCoreLinking() { }
++
++  private:
++    /// Initialization of this is done in lib/IR/IRBuilder.cpp
++    /// because of initialization ordering problems with global
++    /// static variables.  The design of this static initialization
++    /// dependency chain is completely broken.
++    static ForceVMCoreLinking *FVMCL;
++  };
+ }
+ 
+ #endif
++
+###
+--- lib/IR/AttributeImpl.h	2015-08-06 02:49:17.000000000 -0700
++++ lib/IR/AttributeImpl.h	2016-05-09 16:14:24.849498745 -0700
+@@ -186,6 +186,11 @@
+   }
+ };
+ 
++static_assert(AlignOf<AttributeSetNode>::Alignment >=
++              AlignOf<Attribute>::Alignment,
++              "Insufficient alignment for objects appended to "
++              "AttributeSetNode");
++
+ typedef std::pair<unsigned, AttributeSetNode *> IndexAttrPair;
+ 
+ //===----------------------------------------------------------------------===//
+@@ -279,6 +284,11 @@
+   void dump() const;
+ };
+ 
++static_assert(AlignOf<AttributeSetImpl>::Alignment >=
++              AlignOf<IndexAttrPair>::Alignment,
++              "Insufficient alignment for objects appended to "
++              "AttributeSetImpl");
++
+ } // end llvm namespace
+ 
+ #endif
+###
+--- lib/IR/Attributes.cpp	2016-01-03 14:43:40.000000000 -0500
++++ lib/IR/Attributes.cpp	2016-05-08 23:19:20.532430753 -0400
+@@ -1133,8 +1133,8 @@
+ //===----------------------------------------------------------------------===//
+ 
+ AttrBuilder::AttrBuilder(AttributeSet AS, unsigned Index)
+-    : Attrs(0), Alignment(0), StackAlignment(0), DerefBytes(0),
+-      DerefOrNullBytes(0) {
++  : Attrs(0), TargetDepAttrs(), Alignment(0), StackAlignment(0),
++  DerefBytes(0), DerefOrNullBytes(0) {
+   AttributeSetImpl *pImpl = AS.pImpl;
+   if (!pImpl) return;
+ 
+@@ -1185,7 +1185,9 @@
+ }
+ 
+ AttrBuilder &AttrBuilder::addAttribute(StringRef A, StringRef V) {
+-  TargetDepAttrs[A] = V;
++  std::string AS = A.str();
++  std::string VS = V.str();
++  TargetDepAttrs[AS] = VS;
+   return *this;
+ }
+ 
+@@ -1229,9 +1231,11 @@
+ }
+ 
+ AttrBuilder &AttrBuilder::removeAttribute(StringRef A) {
+-  std::map<std::string, std::string>::iterator I = TargetDepAttrs.find(A);
++  std::string AS = A.str();
++  std::map<std::string, std::string>::iterator I = TargetDepAttrs.find(AS);
+   if (I != TargetDepAttrs.end())
+     TargetDepAttrs.erase(I);
++
+   return *this;
+ }
+ 
+@@ -1241,6 +1245,12 @@
+   assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
+   assert(Align <= 0x40000000 && "Alignment too large.");
+ 
++  if (!isPowerOf2_32(Align)) {
++    llvm::errs() << __PRETTY_FUNCTION__
++      << ": Alignment must be a power of two!\n";
++    abort();
++  }
++
+   Attrs[Attribute::Alignment] = true;
+   Alignment = Align;
+   return *this;
+@@ -1333,7 +1343,8 @@
+ }
+ 
+ bool AttrBuilder::contains(StringRef A) const {
+-  return TargetDepAttrs.find(A) != TargetDepAttrs.end();
++  std::string AS = A.str();
++  return TargetDepAttrs.find(AS) != TargetDepAttrs.end();
+ }
+ 
+ bool AttrBuilder::hasAttributes() const {
+@@ -1357,7 +1368,8 @@
+         return true;
+     } else {
+       assert(Attr.isStringAttribute() && "Invalid attribute kind!");
+-      return TargetDepAttrs.find(Attr.getKindAsString())!=TargetDepAttrs.end();
++      std::string AS = Attr.getKindAsString().str();
++      return TargetDepAttrs.find(AS) != TargetDepAttrs.end();
+     }
+   }
+ 
+###
+--- lib/IR/LegacyPassManager.cpp	2016-01-06 17:55:03.000000000 -0500
++++ lib/IR/LegacyPassManager.cpp	2016-05-08 23:19:20.532430753 -0400
+@@ -59,28 +59,27 @@
+   clEnumVal(Details   , "print pass details when it is executed"),
+                              clEnumValEnd));
+ 
+-namespace {
+-typedef llvm::cl::list<const llvm::PassInfo *, bool, PassNameParser>
+-PassOptionList;
+-}
+-
+ // Print IR out before/after specified passes.
+-static PassOptionList
+-PrintBefore("print-before",
+-            llvm::cl::desc("Print IR before specified passes"),
+-            cl::Hidden);
+-
+-static PassOptionList
+-PrintAfter("print-after",
+-           llvm::cl::desc("Print IR after specified passes"),
+-           cl::Hidden);
++static llvm::cl::list<const llvm::PassInfo *, bool, PassNameParser>
++PrintBefore(cl::Prefix, "print-before",
++            cl::desc("Print IR before specified passes"),
++            cl::value_desc("Print IR before specified passes"),
++            cl::Hidden,
++            cl::ZeroOrMore);
++
++static llvm::cl::list<const llvm::PassInfo *, bool, PassNameParser>
++PrintAfter(cl::Prefix, "print-after",
++           cl::desc("Print IR after specified passes"),
++           cl::value_desc("Print IR after specified passes"),
++           cl::Hidden,
++           cl::ZeroOrMore);
+ 
+ static cl::opt<bool>
+-PrintBeforeAll("print-before-all",
++PrintBeforeAll(cl::NormalFormatting, "print-before-all",
+                llvm::cl::desc("Print IR before each pass"),
+                cl::init(false));
+ static cl::opt<bool>
+-PrintAfterAll("print-after-all",
++PrintAfterAll(cl::NormalFormatting, "print-after-all",
+               llvm::cl::desc("Print IR after each pass"),
+               cl::init(false));
+ 
+@@ -94,8 +93,10 @@
+ /// This is a helper to determine whether to print IR before or
+ /// after a pass.
+ 
+-static bool ShouldPrintBeforeOrAfterPass(const PassInfo *PI,
+-                                         PassOptionList &PassesToPrint) {
++static bool
++ShouldPrintBeforeOrAfterPass(const PassInfo *PI,
++                             llvm::cl::list<const llvm::PassInfo *, bool,
++                             PassNameParser> &PassesToPrint) {
+   for (auto *PassInf : PassesToPrint) {
+     if (PassInf)
+       if (PassInf->getPassArgument() == PI->getPassArgument()) {
+###.
+--- lib/IR/Metadata.cpp	2016-01-11 13:37:41.000000000 -0800
++++ lib/IR/Metadata.cpp	2016-05-09 19:35:11.382012208 -0700
+@@ -429,33 +429,75 @@
+       "Alignment is insufficient after objects prepended to " #CLASS);
+ #include "llvm/IR/Metadata.def"
+ 
+-void *MDNode::operator new(size_t Size, unsigned NumOps) {
++void *MDNode::operator new(size_t Size, unsigned NumOps) throw() {
++  assert((Size >= sizeof(MDNode)) && "Insufficient size to operator new!");
++  // MDNode wants to construct its ancillary MDOperands ** BEFORE **
++  // itself.
+   size_t OpSize = NumOps * sizeof(MDOperand);
+   // uint64_t is the most aligned type we need support (ensured by static_assert
+   // above)
+   OpSize = RoundUpToAlignment(OpSize, llvm::alignOf<uint64_t>());
+-  void *Ptr = reinterpret_cast<char *>(::operator new(OpSize + Size)) + OpSize;
+-  MDOperand *O = static_cast<MDOperand *>(Ptr);
+-  for (MDOperand *E = O - NumOps; O != E; --O)
+-    (void)new (O - 1) MDOperand;
+-  return Ptr;
++  std::size_t RSize = Size + OpSize + sizeof(Metadata) + sizeof(uintptr_t);
++  RSize = RoundUpToAlignment(RSize, llvm::alignOf<uint64_t>());
++  std::size_t Alignment = llvm::alignOf<uint64_t>();
++
++  void *P;
++#if defined(_MSC_VER)
++  P = _aligned_malloc(RSize, Alignment);
++  assert(P && "_aligned_malloc failed!");
++  if (!P) return 0;
++#else
++  int R = posix_memalign(&P, Alignment, RSize);
++  assert((R == 0) && "posix_memalign failed!");
++  if (R != 0) return 0;
++#endif
++
++  (void) std::memset(P, 0, RSize);
++  unsigned char *UC = static_cast<unsigned char*>(P);
++  MDNode *MN = reinterpret_cast<MDNode*>((UC + RSize) - Size);
++
++  MDOperand *O = reinterpret_cast<MDOperand*>(MN);
++  MDOperand *MO;
++
++  for (MDOperand *E = O - NumOps; O != E; --O) {
++    MO = new (O - 1) MDOperand();
++    assert(MO && "MDOperand placement new failed!");
++  }
++
++  // We store the address of the aligned allocated buffer
++  // in the last extra element of the buffer. This address
++  // will be used by the corresponding operator delete to
++  // free the correct address.
++  uintptr_t *U = reinterpret_cast<uintptr_t*>(O - 1);
++  *U = reinterpret_cast<uintptr_t>(P);
++  return MN;
++}
++
++void MDNode::operator delete(void *Mem) throw() {
++  MDNode *MN = reinterpret_cast<MDNode *>(Mem);
++  Metadata *MTD = static_cast<Metadata*>(MN);
++  std::size_t OSize = MN->NumOperands * sizeof(MDOperand);
++  OSize = RoundUpToAlignment(OSize, llvm::alignOf<uint64_t>());
++  MDOperand *O = static_cast<MDOperand *>(Mem);
++
++  for (MDOperand *E = O - MN->NumOperands; O != E; --O) {
++    MDOperand *MO = (O - 1);
++    MO->~MDOperand();
+ }
+ 
+-void MDNode::operator delete(void *Mem) {
+-  MDNode *N = static_cast<MDNode *>(Mem);
+-  size_t OpSize = N->NumOperands * sizeof(MDOperand);
+-  OpSize = RoundUpToAlignment(OpSize, llvm::alignOf<uint64_t>());
++  MTD->~Metadata();
++  MN->~MDNode();
+ 
+-  MDOperand *O = static_cast<MDOperand *>(Mem);
+-  for (MDOperand *E = O - N->NumOperands; O != E; --O)
+-    (O - 1)->~MDOperand();
+-  ::operator delete(reinterpret_cast<char *>(Mem) - OpSize);
++  // This is the address of the allocated buffer in the
++  // extra buffer space allocated by operator new.
++  uintptr_t *U = reinterpret_cast<uintptr_t*>(O - 1);
++  std::free(reinterpret_cast<void*>(*U));
+ }
+ 
+-MDNode::MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
++MDNode::MDNode(LLVMContext &Ctx, unsigned ID, StorageType Storage,
+                ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2)
+     : Metadata(ID, Storage), NumOperands(Ops1.size() + Ops2.size()),
+-      NumUnresolved(0), Context(Context) {
++  NumUnresolved(0U), Context(Ctx) {
+   unsigned Op = 0;
+   for (Metadata *MD : Ops1)
+     setOperand(Op++, MD);
+@@ -692,6 +734,9 @@
+     llvm_unreachable("Invalid subclass of MDNode");
+ #define HANDLE_MDNODE_LEAF(CLASS)                                              \
+   case CLASS##Kind:                                                            \
++    static_assert(llvm::AlignOf<uint64_t>::Alignment >=             \
++        llvm::AlignOf<CLASS>::Alignment,                            \
++        "Insufficient alignment for objects prepended to " #CLASS); \
+     delete cast<CLASS>(this);                                                  \
+     break;
+ #include "llvm/IR/Metadata.def"
+@@ -729,6 +774,9 @@
+ #define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS)                                    \
+   case CLASS##Kind: {                                                          \
+     CLASS *SubclassThis = cast<CLASS>(this);                                   \
++    static_assert(llvm::AlignOf<uint64_t>::Alignment >=             \
++        llvm::AlignOf<CLASS>::Alignment,                            \
++        "Insufficient alignment for objects prepended to " #CLASS); \
+     std::integral_constant<bool, HasCachedHash<CLASS>::value>                  \
+         ShouldRecalculateHash;                                                 \
+     dispatchRecalculateHash(SubclassThis, ShouldRecalculateHash);              \
+@@ -744,6 +792,9 @@
+     llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
+ #define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS)                                    \
+   case CLASS##Kind:                                                            \
++    static_assert(llvm::AlignOf<uint64_t>::Alignment >=             \
++        llvm::AlignOf<CLASS>::Alignment,                            \
++        "Insufficient alignment for objects prepended to " #CLASS); \
+     getContext().pImpl->CLASS##s.erase(cast<CLASS>(this));                     \
+     break;
+ #include "llvm/IR/Metadata.def"
+@@ -784,6 +835,9 @@
+     llvm_unreachable("Invalid subclass of MDNode");
+ #define HANDLE_MDNODE_LEAF(CLASS)                                              \
+   case CLASS##Kind: {                                                          \
++    static_assert(llvm::AlignOf<uint64_t>::Alignment >=             \
++        llvm::AlignOf<CLASS>::Alignment,                            \
++        "Insufficient alignment for objects prepended to " #CLASS); \
+     std::integral_constant<bool, HasCachedHash<CLASS>::value> ShouldResetHash; \
+     dispatchResetHash(cast<CLASS>(this), ShouldResetHash);                     \
+     break;                                                                     \
+@@ -1007,6 +1061,88 @@
+ }
+ 
+ //===----------------------------------------------------------------------===//
++// MDTupel implementation.
++//
++void *MDTuple::operator new(size_t Size, unsigned NumOps) throw() {
++  assert((Size >= sizeof(MDTuple)) && "Insufficient size to operator new!");
++
++  std::size_t OSize = NumOps * sizeof(MDOperand);
++  OSize = RoundUpToAlignment(OSize, llvm::alignOf<uint64_t>());
++
++  // Allocate extra space for an uintptr_t at the beginning of the
++  // buffer.  This uintptr_t is where we will store the address of
++  // the memory-aligned storage buffer. It will be plasced immediately
++  // after the last MDOperand.
++  // This address will be computed by the matching operator delete.
++  // The total amount of space allocated must include the Size
++  // parameter passed in. This parameter value is not necessarily
++  // equal to sizeof(MDTuple), it can be greater.
++  std::size_t RSize = Size + OSize + sizeof(MDTuple) + sizeof(uintptr_t);
++  RSize = RoundUpToAlignment(RSize, llvm::alignOf<uint64_t>());
++  std::size_t Alignment = llvm::alignOf<uint64_t>();
++
++  void *P;
++#if defined(_MSC_VER)
++  P = _aligned_malloc(RSize, Alignment);
++  assert(P && "_aligned_malloc failed!");
++  if (!P) return 0;
++#else
++  int R = posix_memalign(&P, Alignment, RSize);
++  assert((R == 0) && "posix_memalign failed!");
++  if (R != 0) return 0;
++#endif
++
++  (void) std::memset(P, 0, RSize);
++
++  // Set a valid pointer to the address which will be returned
++  // by this operator. This will be a pointer to a MDTuple.
++  unsigned char *UC = static_cast<unsigned char*>(P);
++  MDTuple *MDT = reinterpret_cast<MDTuple*>((UC + RSize) - Size);
++  MDNode *MN = static_cast<MDNode*>(MDT);
++
++  MDOperand *O = reinterpret_cast<MDOperand*>(MN);
++  MDOperand *MO;
++
++  for (MDOperand *E = O - NumOps; O != E; --O) {
++    MO = new (O - 1) MDOperand();
++    assert(MO && "MDOperand placement new failed!");
++  }
++
++  // We store the address of the aligned allocated buffer
++  // in the last extra element of the buffer. This address
++  // will be used by the corresponding operator delete to
++  // free the correct address.
++  uintptr_t *U = reinterpret_cast<uintptr_t*>(O - 1);
++  *U = reinterpret_cast<uintptr_t>(P);
++  return MDT;
++}
++
++void MDTuple::operator delete(void *Mem) throw() {
++  MDTuple *MDT = reinterpret_cast<MDTuple*>(Mem);
++  // UniquableMDNode *UMN = static_cast<UniquableMDNode*>(MDT);
++  MDNode *MN = static_cast<MDNode*>(MDT);
++  unsigned NumOperands = MN->getNumOperands();
++
++  std::size_t OSize = NumOperands * sizeof(MDOperand);
++  OSize = RoundUpToAlignment(OSize, llvm::alignOf<uint64_t>());
++
++  MDOperand *O =
++    reinterpret_cast<MDOperand*>(reinterpret_cast<void*>(MN));
++  for (MDOperand *E = O - NumOperands; O != E; --O) {
++    MDOperand *MO = (O - 1);
++    MO->~MDOperand();
++  }
++
++  // This is teh address of the allocated buffer in the
++  // extra space allocated by operator new in RSize.
++  uintptr_t *U = reinterpret_cast<uintptr_t*>(O - 1);
++
++  // UMN->~UniquableMDNode();
++  MDT->~MDTuple();
++  std::free(reinterpret_cast<void*>(*U));
++}
++
++//===----------------------------------------------------------------------===//
+ // NamedMDNode implementation.
+ //
+ 
--- a/components/llvm/patches/005-Makefile.patch	Thu Jul 28 16:15:45 2016 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,22 +0,0 @@
-# Solaris autoconf-based build.
-# https://llvm.org/bugs/show_bug.cgi?id=24641
---- tools/clang/tools/libclang/Makefile	2014-10-29 11:55:09.000000000 -0700
-+++ tools/clang/tools/libclang/Makefile	2015-06-10 15:18:27.471754914 -0700
-@@ -33,10 +33,16 @@
- include $(CLANG_LEVEL)/Makefile
- 
- # Add soname to the library.
--ifeq ($(HOST_OS), $(filter $(HOST_OS), Linux FreeBSD GNU GNU/kFreeBSD))
-+ifeq ($(HOST_OS), $(filter $(HOST_OS), Linux FreeBSD GNU GNU/kFreeBSD SunOS))
-         LLVMLibsOptions += -Wl,-soname,lib$(LIBRARYNAME)$(SHLIBEXT)
- endif
- 
-+# Extract everything necessary from Solaris *.a archives
-+ifeq ($(HOST_OS), $(filter $(HOST_OS), SunOS))
-+  SharedLinkOptions += -Wl,-z -Wl,rescan-now -Wl,-z -Wl,allextract
-+  LLVMLibsOptions += -Wl,-z -Wl,defaultextract
-+endif
-+
- ifeq ($(ENABLE_CLANG_ARCMT),1)
-   CXX.Flags += -DCLANG_ENABLE_ARCMT
- endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/005-solaris-LLVM-libLLVMMC.patch	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,502 @@
+# 22902339 memory corruption caused by undefined behavior in LLVM IR Module
+# Miscellaneous cleanup fixes (bitfields).
+# 3.8.X upstream. Alghouth they love bitfields.
+--- include/llvm/MC/MCSection.h	2015-12-29 04:06:16.000000000 -0500
++++ include/llvm/MC/MCSection.h	2016-05-08 23:19:20.520430461 -0400
+@@ -67,14 +67,17 @@
+ 
+ private:
+   MCSection(const MCSection &) = delete;
+-  void operator=(const MCSection &) = delete;
++  MCSection &operator=(const MCSection &) = delete;
+ 
+   MCSymbol *Begin;
+   MCSymbol *End = nullptr;
++
+   /// The alignment requirement of this section.
+   unsigned Alignment = 1;
++
+   /// The section index in the assemblers section list.
+   unsigned Ordinal = 0;
++
+   /// The index of this section in the layout order.
+   unsigned LayoutOrder;
+ 
+@@ -86,12 +89,12 @@
+ 
+   /// \brief We've seen a bundle_lock directive but not its first instruction
+   /// yet.
+-  unsigned BundleGroupBeforeFirstInst : 1;
++  bool BundleGroupBeforeFirstInst;
+ 
+   /// Whether this section has had instructions emitted into it.
+-  unsigned HasInstructions : 1;
++  bool HasInstructions;
+ 
+-  unsigned IsRegistered : 1;
++  bool IsRegistered;
+ 
+   MCDummyFragment DummyFragment;
+ 
+@@ -105,9 +108,9 @@
+   MCSection(SectionVariant V, SectionKind K, MCSymbol *Begin);
+   SectionVariant Variant;
+   SectionKind Kind;
+-  ~MCSection();
+ 
+ public:
++  virtual ~MCSection();
+   SectionKind getKind() const { return Kind; }
+ 
+   SectionVariant getVariant() const { return Variant; }
+--- include/llvm/MC/MCStreamer.h	2016-01-12 08:38:15.000000000 -0500
++++ include/llvm/MC/MCStreamer.h	2016-05-08 23:19:20.520430461 -0400
+@@ -464,6 +464,13 @@
+   ///  .size symbol, expression
+   virtual void emitELFSize(MCSymbolELF *Symbol, const MCExpr *Value);
+ 
++  /// EmitELFSize - Emit an ELF .size directive.
++  ///
++  /// This corresponds to an assembler statement such as:
++  ///  .size symbol, expression, but without a temp .label.
++  ///
++  virtual void EmitELFSize(StringRef Name);
++
+   /// \brief Emit a Linker Optimization Hint (LOH) directive.
+   /// \param Args - Arguments of the LOH.
+   virtual void EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) {}
+--- include/llvm/MC/MCSymbol.h	2015-10-05 05:07:05.000000000 -0700
++++ include/llvm/MC/MCSymbol.h	2016-05-09 10:02:49.488583805 -0700
+@@ -29,6 +29,23 @@
+ class MCContext;
+ class raw_ostream;
+ 
++#if 0
++/// \brief The name for a symbol.
++/// MCSymbol contains a uint64_t so is probably aligned to 8.  On a 32-bit
++/// system, the name is a pointer so isn't going to satisfy the 8 byte
++/// alignment of uint64_t.  Account for that here.
++/// Clueless. std::uin64_t aligns on 4 on 32-bit Intel (psABI).
++typedef union {
++  const StringMapEntry<bool> *NameEntry;
++  uint64_t AlignmentPadding;
++  uint64_t Buffer[2];
++} NameEntryStorageTy;
++
++static_assert(llvm::AlignOf<llvm::NameEntryStorageTy>::Alignment >=
++              llvm::AlignOf<uint64_t>::Alignment,
++              "Insufficient alignment for llvm::NameEntryStorageTy!");
++#endif
++
+ /// MCSymbol - Instances of this class represent a symbol name in the MC file,
+ /// and MCSymbols are created and uniqued by the MCContext class.  MCSymbols
+ /// should only be constructed with valid names for the object file.
+@@ -49,7 +66,7 @@
+ 
+   /// A symbol can contain an Offset, or Value, or be Common, but never more
+   /// than one of these.
+-  enum Contents : uint8_t {
++  enum Contents {
+     SymContentsUnset,
+     SymContentsOffset,
+     SymContentsVariable,
+@@ -79,48 +96,49 @@
+   /// 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;
++  bool IsTemporary;
+ 
+   /// \brief True if this symbol can be redefined.
+-  unsigned IsRedefinable : 1;
++  bool IsRedefinable;
+ 
+   /// IsUsed - True if this symbol has been used.
+-  mutable unsigned IsUsed : 1;
++  mutable bool IsUsed;
+ 
+-  mutable bool IsRegistered : 1;
++  mutable bool IsRegistered;
+ 
+   /// This symbol is visible outside this translation unit.
+-  mutable unsigned IsExternal : 1;
++  mutable bool IsExternal;
+ 
+   /// This symbol is private extern.
+-  mutable unsigned IsPrivateExtern : 1;
++  mutable bool IsPrivateExtern;
+ 
+   /// LLVM RTTI discriminator. This is actually a SymbolKind enumerator, but is
+   /// unsigned to avoid sign extension and achieve better bitpacking with MSVC.
+-  unsigned Kind : 2;
++  unsigned Kind;
+ 
+   /// True if we have created a relocation that uses this symbol.
+-  mutable unsigned IsUsedInReloc : 1;
++  mutable bool IsUsedInReloc;
+ 
+   /// This is actually a Contents enumerator, but is unsigned to avoid sign
+   /// extension and achieve better bitpacking with MSVC.
+-  unsigned SymbolContents : 2;
++  unsigned SymbolContents;
+ 
+   /// The alignment of the symbol, if it is 'common', or -1.
+   ///
+   /// The alignment is stored as log2(align) + 1.  This allows all values from
+   /// 0 to 2^31 to be stored which is every power of 2 representable by an
+   /// unsigned.
+-  enum : unsigned { NumCommonAlignmentBits = 5 };
+-  unsigned CommonAlignLog2 : NumCommonAlignmentBits;
++  enum { NumCommonAlignmentBits = 5 };
++  unsigned CommonAlignLog2;
+ 
+   /// The Flags field is used by object file implementations to store
+   /// additional per symbol information which is not easily classified.
+-  enum : unsigned { NumFlagsBits = 16 };
+-  mutable uint32_t Flags : NumFlagsBits;
++  enum { NumFlagsBits = 16 };
++
++  mutable uint32_t Flags;
+ 
+   /// Index field, for use by the object file implementation.
+-  mutable uint32_t Index = 0;
++  mutable uint32_t Index;
+ 
+   union {
+     /// The offset to apply to the fragment address to form this symbol's value.
+@@ -131,27 +149,32 @@
+ 
+     /// If non-null, the value for a variable symbol.
+     const MCExpr *Value;
++    uint64_t Buffer[4];
+   };
+ 
+ protected: // MCContext creates and uniques these.
+   friend class MCExpr;
+   friend class MCContext;
+ 
++public:
+   /// \brief The name for a symbol.
+   /// MCSymbol contains a uint64_t so is probably aligned to 8.  On a 32-bit
+   /// system, the name is a pointer so isn't going to satisfy the 8 byte
+   /// alignment of uint64_t.  Account for that here.
++  /// This implementation makes absolutely no sense whatsoever.
+   typedef union {
+     const StringMapEntry<bool> *NameEntry;
+     uint64_t AlignmentPadding;
++    uint64_t Buffer[2];
+   } NameEntryStorageTy;
+ 
+   MCSymbol(SymbolKind Kind, const StringMapEntry<bool> *Name, bool isTemporary)
+       : IsTemporary(isTemporary), IsRedefinable(false), IsUsed(false),
+         IsRegistered(false), IsExternal(false), IsPrivateExtern(false),
+         Kind(Kind), IsUsedInReloc(false), SymbolContents(SymContentsUnset),
+-        CommonAlignLog2(0), Flags(0) {
+-    Offset = 0;
++  CommonAlignLog2(0U), Flags(0U), Index(0U) {
++    (void) std::memset(Buffer, 0, sizeof(Buffer));
++    Offset = 0U;
+     FragmentAndHasName.setInt(!!Name);
+     if (Name)
+       getNameEntryPtr() = Name;
+@@ -163,19 +186,25 @@
+                      MCContext &Ctx);
+ 
+ private:
+-
+   void operator delete(void *);
++
+   /// \brief Placement delete - required by std, but never called.
+   void operator delete(void*, unsigned) {
+-    llvm_unreachable("Constructor throws?");
++    llvm::errs() << __PRETTY_FUNCTION__
++      << ": this should never happend!\n";
++    abort();
+   }
++
+   /// \brief Placement delete - required by std, but never called.
+   void operator delete(void*, unsigned, bool) {
+-    llvm_unreachable("Constructor throws?");
++    llvm::errs() << __PRETTY_FUNCTION__
++      << ": this should never happend!\n";
++    abort();
+   }
+ 
+   MCSymbol(const MCSymbol &) = delete;
+-  void operator=(const MCSymbol &) = delete;
++  MCSymbol &operator=(const MCSymbol &) = delete;
++
+   MCSection *getSectionPtr(bool SetUsed = true) const {
+     if (MCFragment *F = getFragment(SetUsed)) {
+       assert(F != AbsolutePseudoFragment);
+@@ -190,6 +219,7 @@
+     NameEntryStorageTy *Name = reinterpret_cast<NameEntryStorageTy *>(this);
+     return (*(Name - 1)).NameEntry;
+   }
++
+   const StringMapEntry<bool> *&getNameEntryPtr() const {
+     return const_cast<MCSymbol*>(this)->getNameEntryPtr();
+   }
+@@ -412,6 +442,14 @@
+   }
+ };
+ 
++static_assert(llvm::AlignOf<llvm::MCSymbol>::Alignment >=
++              llvm::AlignOf<uint64_t>::Alignment,
++              "Insufficient alignment for llvm::MCSymbol!");
++
++static_assert(llvm::AlignOf<llvm::MCSymbol::NameEntryStorageTy>::Alignment >=
++              llvm::AlignOf<uint64_t>::Alignment,
++              "Insufficient alignment for llvm::MCSymbol::NameEntryStorageTy!");
++
+ inline raw_ostream &operator<<(raw_ostream &OS, const MCSymbol &Sym) {
+   Sym.print(OS, nullptr);
+   return OS;
+###
+--- lib/MC/MCAsmStreamer.cpp	2015-11-12 04:33:00.000000000 -0900
++++ lib/MC/MCAsmStreamer.cpp	2016-07-07 11:33:34.645300365 -0800
+@@ -46,30 +46,37 @@
+   std::unique_ptr<MCCodeEmitter> Emitter;
+   std::unique_ptr<MCAsmBackend> AsmBackend;
+ 
+-  SmallString<128> CommentToEmit;
++  SmallString<1024> CommentToEmit;
+   raw_svector_ostream CommentStream;
+ 
+-  unsigned IsVerboseAsm : 1;
+-  unsigned ShowInst : 1;
+-  unsigned UseDwarfDirectory : 1;
++  bool IsVerboseAsm;
++  bool ShowInst;
++  bool UseDwarfDirectory;
+ 
+   void EmitRegisterName(int64_t Register);
+   void EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) override;
+   void EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) override;
+ 
+ public:
+-  MCAsmStreamer(MCContext &Context, std::unique_ptr<formatted_raw_ostream> os,
++  MCAsmStreamer(MCContext &Context,
++                std::unique_ptr<formatted_raw_ostream> os,
+                 bool isVerboseAsm, bool useDwarfDirectory,
+                 MCInstPrinter *printer, MCCodeEmitter *emitter,
+                 MCAsmBackend *asmbackend, bool showInst)
+-      : MCStreamer(Context), OSOwner(std::move(os)), OS(*OSOwner),
+-        MAI(Context.getAsmInfo()), InstPrinter(printer), Emitter(emitter),
+-        AsmBackend(asmbackend), CommentStream(CommentToEmit),
+-        IsVerboseAsm(isVerboseAsm), ShowInst(showInst),
+-        UseDwarfDirectory(useDwarfDirectory) {
++  : MCStreamer(Context),
++  OSOwner(std::move(os)),
++  OS(*OSOwner),
++  MAI(Context.getAsmInfo()),
++  InstPrinter(printer),
++  Emitter(emitter),
++  AsmBackend(asmbackend),
++  CommentStream(CommentToEmit),
++  IsVerboseAsm(isVerboseAsm),
++  ShowInst(showInst),
++  UseDwarfDirectory(useDwarfDirectory) {
+     assert(InstPrinter);
+     if (IsVerboseAsm)
+-        InstPrinter->setCommentStream(CommentStream);
++      InstPrinter->setCommentStream(CommentStream);
+   }
+ 
+   inline void EmitEOL() {
+@@ -78,6 +85,7 @@
+       OS << '\n';
+       return;
+     }
++
+     EmitCommentsAndEOL();
+   }
+ 
+@@ -145,6 +153,7 @@
+   void EmitCOFFSectionIndex(MCSymbol const *Symbol) override;
+   void EmitCOFFSecRel32(MCSymbol const *Symbol) override;
+   void emitELFSize(MCSymbolELF *Symbol, const MCExpr *Value) override;
++  void EmitELFSize(StringRef Name) override;
+   void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
+                         unsigned ByteAlignment) override;
+ 
+@@ -540,6 +549,11 @@
+   OS << '\n';
+ }
+ 
++void MCAsmStreamer::EmitELFSize(StringRef Name) {
++  assert(MAI->hasDotTypeDotSizeDirective());
++  OS << "\t.size\t" << Name << ", .-" << Name << '\n';
++}
++
+ void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
+                                      unsigned ByteAlignment) {
+   OS << "\t.comm\t";
+@@ -889,7 +903,7 @@
+   if (NumFiles == Table.getMCDwarfFiles().size())
+     return FileNo;
+ 
+-  SmallString<128> FullPathName;
++  SmallString<PATH_MAX> FullPathName;
+ 
+   if (!UseDwarfDirectory && !Directory.empty()) {
+     if (sys::path::is_absolute(Filename))
+@@ -1240,7 +1254,7 @@
+ void MCAsmStreamer::AddEncodingComment(const MCInst &Inst,
+                                        const MCSubtargetInfo &STI) {
+   raw_ostream &OS = GetCommentOS();
+-  SmallString<256> Code;
++  SmallString<1024> Code;
+   SmallVector<MCFixup, 4> Fixups;
+   raw_svector_ostream VecOS(Code);
+   Emitter->encodeInstruction(Inst, VecOS, Fixups, STI);
+###
+--- lib/MC/MCSectionELF.cpp	2015-11-06 10:30:45.000000000 -0500
++++ lib/MC/MCSectionELF.cpp	2016-05-08 23:19:20.534430801 -0400
+@@ -70,33 +70,18 @@
+   OS << "\t.section\t";
+   printName(OS, getSectionName());
+ 
+-  // Handle the weird solaris syntax if desired.
+-  if (MAI.usesSunStyleELFSectionSwitchSyntax() &&
+-      !(Flags & ELF::SHF_MERGE)) {
+-    if (Flags & ELF::SHF_ALLOC)
+-      OS << ",#alloc";
+-    if (Flags & ELF::SHF_EXECINSTR)
+-      OS << ",#execinstr";
+-    if (Flags & ELF::SHF_WRITE)
+-      OS << ",#write";
+-    if (Flags & ELF::SHF_EXCLUDE)
+-      OS << ",#exclude";
+-    if (Flags & ELF::SHF_TLS)
+-      OS << ",#tls";
+-    OS << '\n';
+-    return;
+-  }
+-
+   OS << ",\"";
+   if (Flags & ELF::SHF_ALLOC)
+     OS << 'a';
+   if (Flags & ELF::SHF_EXCLUDE)
+     OS << 'e';
+-  if (Flags & ELF::SHF_EXECINSTR)
++  if ((Flags & ELF::SHF_EXECINSTR) && (Type != ELF::SHT_INIT_ARRAY) &&
++      (Type != ELF::SHT_FINI_ARRAY) && (Type != ELF::SHT_PREINIT_ARRAY))
+     OS << 'x';
+   if (Flags & ELF::SHF_GROUP)
+     OS << 'G';
+-  if (Flags & ELF::SHF_WRITE)
++  if ((Flags & ELF::SHF_WRITE) || (Type == ELF::SHT_INIT_ARRAY) ||
++      (Type == ELF::SHT_FINI_ARRAY) || (Type == ELF::SHT_PREINIT_ARRAY))
+     OS << 'w';
+   if (Flags & ELF::SHF_MERGE)
+     OS << 'M';
+--- lib/MC/MCStreamer.cpp	2015-11-04 18:59:18.000000000 -0500
++++ lib/MC/MCStreamer.cpp	2016-05-08 23:19:20.534430801 -0400
+@@ -680,6 +680,7 @@
+ void MCStreamer::EmitCOFFSymbolStorageClass(int StorageClass) {}
+ void MCStreamer::EmitCOFFSymbolType(int Type) {}
+ void MCStreamer::emitELFSize(MCSymbolELF *Symbol, const MCExpr *Value) {}
++void MCStreamer::EmitELFSize(StringRef Name) { }
+ void MCStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
+                                        unsigned ByteAlignment) {}
+ void MCStreamer::EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
+####
+--- lib/MC/MCContext.cpp	2015-12-16 14:49:14.000000000 -0900
++++ lib/MC/MCContext.cpp	2016-07-07 11:27:58.976687075 -0800
+@@ -108,7 +108,7 @@
+ //===----------------------------------------------------------------------===//
+ 
+ MCSymbol *MCContext::getOrCreateSymbol(const Twine &Name) {
+-  SmallString<128> NameSV;
++  SmallString<1024> NameSV;
+   StringRef NameRef = Name.toStringRef(NameSV);
+ 
+   assert(!NameRef.empty() && "Normal symbols cannot be unnamed!");
+@@ -185,7 +185,7 @@
+   if (AllowTemporaryLabels && !IsTemporary)
+     IsTemporary = Name.startswith(MAI->getPrivateGlobalPrefix());
+ 
+-  SmallString<128> NewName = Name;
++  SmallString<1024> NewName = Name;
+   bool AddSuffix = AlwaysAddSuffix;
+   unsigned &NextUniqueID = NextID[Name];
+   for (;;) {
+@@ -207,13 +207,13 @@
+ 
+ MCSymbol *MCContext::createTempSymbol(const Twine &Name, bool AlwaysAddSuffix,
+                                       bool CanBeUnnamed) {
+-  SmallString<128> NameSV;
++  SmallString<1024> NameSV;
+   raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name;
+   return createSymbol(NameSV, AlwaysAddSuffix, CanBeUnnamed);
+ }
+ 
+ MCSymbol *MCContext::createLinkerPrivateTempSymbol() {
+-  SmallString<128> NameSV;
++  SmallString<1024> NameSV;
+   raw_svector_ostream(NameSV) << MAI->getLinkerPrivateGlobalPrefix() << "tmp";
+   return createSymbol(NameSV, true, false);
+ }
+@@ -277,7 +277,7 @@
+   // diagnosed by the client as an error.
+ 
+   // Form the name to look up.
+-  SmallString<64> Name;
++  SmallString<1024> Name;
+   Name += Segment;
+   Name.push_back(',');
+   Name += Section;
+####
+--- lib/MC/MCSymbol.cpp	2015-12-29 00:32:18.000000000 -0900
++++ lib/MC/MCSymbol.cpp	2016-07-07 14:33:23.830913215 -0800
+@@ -16,26 +16,42 @@
+ #include "llvm/Support/raw_ostream.h"
+ using namespace llvm;
+ 
++#include <stdlib.h>
++
+ // Only the address of this fragment is ever actually used.
+ static MCDummyFragment SentinelFragment(nullptr);
+ 
+ // Sentinel value for the absolute pseudo fragment.
+ MCFragment *MCSymbol::AbsolutePseudoFragment = &SentinelFragment;
+ 
+-void *MCSymbol::operator new(size_t s, const StringMapEntry<bool> *Name,
++void *MCSymbol::operator new(size_t S, const StringMapEntry<bool> *Name,
+                              MCContext &Ctx) {
+   // We may need more space for a Name to account for alignment.  So allocate
+   // space for the storage type and not the name pointer.
+-  size_t Size = s + (Name ? sizeof(NameEntryStorageTy) : 0);
++  unsigned NL = Name ?
++    Name->getKeyLength() + sizeof(bool) + sizeof(uint64_t) :
++    256U + sizeof(bool) + sizeof(uint64_t);
++  NL = llvm::RoundUpToAlignment(NL, alignof(uint64_t));
++  size_t Size = S + NL;
+ 
+   // For safety, ensure that the alignment of a pointer is enough for an
+   // MCSymbol.  This also ensures we don't need padding between the name and
+   // symbol.
+-  static_assert((unsigned)AlignOf<MCSymbol>::Alignment <=
+-                AlignOf<NameEntryStorageTy>::Alignment,
+-                "Bad alignment of MCSymbol");
+-  void *Storage = Ctx.allocate(Size, alignOf<NameEntryStorageTy>());
+-  NameEntryStorageTy *Start = static_cast<NameEntryStorageTy*>(Storage);
++  static_assert(llvm::AlignOf<MCSymbol>::Alignment >=
++                llvm::AlignOf<llvm::MCSymbol::NameEntryStorageTy>::Alignment,
++                "Insufficient alignment for MCSymbol::NameEntryStorageTy!");
++
++  static_assert(llvm::AlignOf<MCSymbol>::Alignment >=
++                llvm::AlignOf<uint64_t>::Alignment,
++                "Insufficient alignment for MCSymbol!");
++
++  unsigned Alignment =
++    static_cast<unsigned>(llvm::AlignOf<llvm::MCSymbol>::Alignment);
++  uint64_t *Storage =
++    reinterpret_cast<uint64_t*>(Ctx.allocate(Size, Alignment));
++  assert(Storage && "MCContext memory allocation failure!");
++
++  NameEntryStorageTy *Start = reinterpret_cast<NameEntryStorageTy*>(Storage);
+   NameEntryStorageTy *End = Start + (Name ? 1 : 0);
+   return End;
+ }
--- a/components/llvm/patches/006-clang-D10272.patch	Thu Jul 28 16:15:45 2016 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,1767 +0,0 @@
-# Giant clang 3.6.2 patch for correcting misalignments.
-# Patch is from: http://reviews.llvm.org/D10272
-# Adjustments were made for 3.6.2 (the original does not apply cleanly).
---- include/llvm/Support/Compiler.h	2014-11-18 17:17:30.000000000 -0500
-+++ include/llvm/Support/Compiler.h	2015-07-17 23:43:07.143745400 -0400
-@@ -303,6 +303,37 @@
- # define LLVM_ASSUME_ALIGNED(p, a) (p)
- #endif
- 
-+/// \macro LLVM_ALIGNAS
-+/// \brief Used to specify a minimum alignment for a structure or variable. The
-+/// alignment must be a constant integer. Use LLVM_PTR_SIZE to compute
-+/// alignments in terms of the size of a pointer.
-+///
-+/// Note that __declspec(align) has special quirks, it's not legal to pass a
-+/// structure with __declspec(align) as a formal parameter.
-+#ifdef _MSC_VER
-+# define LLVM_ALIGNAS(x) __declspec(align(x))
-+#elif __GNUC__ && !__has_feature(cxx_alignas) && !LLVM_GNUC_PREREQ(4, 8, 0)
-+# define LLVM_ALIGNAS(x) __attribute__((aligned(x)))
-+#else
-+# define LLVM_ALIGNAS(x) alignas(x)
-+#endif
-+
-+/// \macro LLVM_PTR_SIZE
-+/// \brief A constant integer equivalent to the value of sizeof(void*).
-+/// Generally used in combination with LLVM_ALIGNAS or when doing computation in
-+/// the preprocessor.
-+#ifdef __SIZEOF_POINTER__
-+# define LLVM_PTR_SIZE __SIZEOF_POINTER__
-+#elif defined(_WIN64)
-+# define LLVM_PTR_SIZE 8
-+#elif defined(_WIN32)
-+# define LLVM_PTR_SIZE 4
-+#elif defined(_MSC_VER)
-+# error "could not determine LLVM_PTR_SIZE as a constant int for MSVC"
-+#else
-+# define LLVM_PTR_SIZE sizeof(void *)
-+#endif
-+
- /// \macro LLVM_FUNCTION_NAME
- /// \brief Expands to __func__ on compilers which support it.  Otherwise,
- /// expands to a compiler-dependent replacement.
---- tools/clang/include/clang/AST/Decl.h	2015-01-13 16:31:13.000000000 -0800
-+++ tools/clang/include/clang/AST/Decl.h	2015-07-17 16:43:46.474996996 -0700
-@@ -3658,6 +3658,9 @@
-   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
-   static bool classofKind(Kind K) { return K == Import; }
- };
-+static_assert(llvm::AlignOf<ImportDecl>::Alignment >=
-+                  llvm::AlignOf<SourceLocation>::Alignment,
-+              "Alignment is insufficient for objects appended to ImportDecl");
- 
- /// \brief Represents an empty-declaration.
- class EmptyDecl : public Decl {
---- tools/clang/include/clang/AST/DeclBase.h	2014-11-17 15:36:45.000000000 -0800
-+++ tools/clang/include/clang/AST/DeclBase.h	2015-07-17 16:43:46.476997606 -0700
-@@ -69,6 +69,9 @@
- /// Decl - This represents one declaration (or definition), e.g. a variable,
- /// typedef, function, struct, etc.
- ///
-+/// Note: There are objects tacked on before the *beginning* of Decl
-+/// (and its subclasses) in its Decl::operator new(). Proper alignment
-+/// for all subclasses is asserted in DeclBase.cpp.
- class Decl {
- public:
-   /// \brief Lists the kind of concrete classes of Decl.
---- tools/clang/include/clang/AST/DeclCXX.h	2014-12-10 12:04:48.000000000 -0800
-+++ tools/clang/include/clang/AST/DeclCXX.h	2015-07-17 16:43:46.479237326 -0700
-@@ -2130,6 +2130,10 @@
-   /// \brief Get the initializer.
-   Expr *getInit() const { return static_cast<Expr*>(Init); }
- };
-+static_assert(
-+    llvm::AlignOf<CXXCtorInitializer>::Alignment >=
-+        llvm::AlignOf<VarDecl *>::Alignment,
-+    "Alignment is insufficient for objects appended to CXXCtorInitializer");
- 
- /// \brief Represents a C++ constructor within a class.
- ///
---- tools/clang/include/clang/AST/DeclFriend.h	2014-07-16 18:59:34.000000000 -0700
-+++ tools/clang/include/clang/AST/DeclFriend.h	2015-07-17 16:43:46.480506828 -0700
-@@ -172,6 +172,9 @@
-   friend class ASTDeclReader;
-   friend class ASTDeclWriter;
- };
-+static_assert(llvm::AlignOf<FriendDecl>::Alignment >=
-+                  llvm::AlignOf<TemplateParameterList *>::Alignment,
-+              "Alignment is insufficient for objects appended to FriendDecl");
- 
- /// An iterator over the friend declarations of a class.
- class CXXRecordDecl::friend_iterator {
---- tools/clang/include/clang/AST/DeclGroup.h	2014-05-05 23:48:52.000000000 -0700
-+++ tools/clang/include/clang/AST/DeclGroup.h	2015-07-17 16:43:46.481808784 -0700
-@@ -14,6 +14,7 @@
- #ifndef LLVM_CLANG_AST_DECLGROUP_H
- #define LLVM_CLANG_AST_DECLGROUP_H
- 
-+#include "llvm/Support/AlignOf.h"
- #include "llvm/Support/DataTypes.h"
- #include <cassert>
- 
-@@ -51,6 +52,9 @@
-     return ((Decl* const*) (this+1))[i];
-   }
- };
-+static_assert(llvm::AlignOf<DeclGroup>::Alignment >=
-+                  llvm::AlignOf<Decl *>::Alignment,
-+              "Alignment is insufficient for objects appended to DeclGroup");
- 
- class DeclGroupRef {
-   // Note this is not a PointerIntPair because we need the address of the
---- tools/clang/include/clang/AST/DeclOpenMP.h	2014-11-10 20:05:39.000000000 -0800
-+++ tools/clang/include/clang/AST/DeclOpenMP.h	2015-07-17 16:43:46.482893197 -0700
-@@ -84,6 +84,10 @@
-   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
-   static bool classofKind(Kind K) { return K == OMPThreadPrivate; }
- };
-+static_assert(
-+    llvm::AlignOf<OMPThreadPrivateDecl>::Alignment >=
-+        llvm::AlignOf<Expr *>::Alignment,
-+    "Alignment is insufficient for objects appended to OMPThreadPrivateDecl");
- 
- }  // end namespace clang
- 
---- tools/clang/include/clang/AST/DeclTemplate.h	2014-08-30 09:55:39.000000000 -0700
-+++ tools/clang/include/clang/AST/DeclTemplate.h	2015-07-17 16:43:46.485713092 -0700
-@@ -43,7 +43,7 @@
- 
- /// \brief Stores a list of template parameters for a TemplateDecl and its
- /// derived classes.
--class TemplateParameterList {
-+class LLVM_ALIGNAS(/*alignof(void*)*/ LLVM_PTR_SIZE) TemplateParameterList {
-   /// The location of the 'template' keyword.
-   SourceLocation TemplateLoc;
- 
-@@ -131,6 +131,10 @@
-     return SourceRange(TemplateLoc, RAngleLoc);
-   }
- };
-+static_assert(
-+    llvm::AlignOf<TemplateParameterList>::Alignment >=
-+        llvm::AlignOf<NamedDecl *>::Alignment,
-+    "Alignment is insufficient for objects appended to TemplateParameterList");
- 
- /// \brief Stores a list of template parameters for a TemplateDecl and its
- /// derived classes. Suitable for creating on the stack.
-@@ -460,27 +464,20 @@
- ///     friend void foo<>(T);
- ///   };
- /// \endcode
--class DependentFunctionTemplateSpecializationInfo {
--  struct CA {
-+class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8)
-+    DependentFunctionTemplateSpecializationInfo {
-     /// The number of potential template candidates.
-     unsigned NumTemplates;
- 
-     /// The number of template arguments.
-     unsigned NumArgs;
--  };
--
--  union {
--    // Force sizeof to be a multiple of sizeof(void*) so that the
--    // trailing data is aligned.
--    void *Aligner;
--    struct CA d;
--  };
- 
-   /// The locations of the left and right angle brackets.
-   SourceRange AngleLocs;
- 
-   FunctionTemplateDecl * const *getTemplates() const {
--    return reinterpret_cast<FunctionTemplateDecl*const*>(this+1);
-+    return reinterpret_cast<FunctionTemplateDecl *const *>(
-+        &getTemplateArgs()[NumArgs]);
-   }
- 
- public:
-@@ -490,9 +487,7 @@
- 
-   /// \brief Returns the number of function templates that this might
-   /// be a specialization of.
--  unsigned getNumTemplates() const {
--    return d.NumTemplates;
--  }
-+  unsigned getNumTemplates() const { return NumTemplates; }
- 
-   /// \brief Returns the i'th template candidate.
-   FunctionTemplateDecl *getTemplate(unsigned I) const {
-@@ -502,14 +497,11 @@
- 
-   /// \brief Returns the explicit template arguments that were given.
-   const TemplateArgumentLoc *getTemplateArgs() const {
--    return reinterpret_cast<const TemplateArgumentLoc*>(
--                                            &getTemplates()[getNumTemplates()]);
-+    return reinterpret_cast<const TemplateArgumentLoc *>(this + 1);
-   }
- 
-   /// \brief Returns the number of explicit template arguments that were given.
--  unsigned getNumTemplateArgs() const {
--    return d.NumArgs;
--  }
-+  unsigned getNumTemplateArgs() const { return NumArgs; }
- 
-   /// \brief Returns the nth template argument.
-   const TemplateArgumentLoc &getTemplateArg(unsigned I) const {
-@@ -525,6 +517,15 @@
-     return AngleLocs.getEnd();
-   }
- };
-+static_assert(
-+    llvm::AlignOf<DependentFunctionTemplateSpecializationInfo>::Alignment >=
-+        llvm::AlignOf<TemplateArgumentLoc>::Alignment,
-+    "Alignment is insufficient for objects appended to "
-+    "DependentFunctionTemplateSpecializationInfo");
-+static_assert(llvm::AlignOf<TemplateArgumentLoc>::Alignment >=
-+                  llvm::AlignOf<FunctionTemplateDecl *>::Alignment,
-+              "Alignment is insufficient for objects appended to "
-+              "DependentFunctionTemplateSpecializationInfo");
- 
- /// Declaration of a redeclarable template.
- class RedeclarableTemplateDecl : public TemplateDecl, 
-@@ -1203,6 +1204,10 @@
-   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
-   static bool classofKind(Kind K) { return K == NonTypeTemplateParm; }
- };
-+static_assert(llvm::AlignOf<NonTypeTemplateParmDecl>::Alignment >=
-+                  llvm::AlignOf<void *>::Alignment,
-+              "Alignment is insufficient for objects appended to "
-+              "NonTypeTemplateParmDecl");
- 
- /// TemplateTemplateParmDecl - Declares a template template parameter,
- /// e.g., "T" in
-@@ -1369,6 +1374,10 @@
-   friend class ASTDeclReader;
-   friend class ASTDeclWriter;
- };
-+static_assert(llvm::AlignOf<TemplateTemplateParmDecl>::Alignment >=
-+                  llvm::AlignOf<TemplateParameterList *>::Alignment,
-+              "Alignment is insufficient for objects appended to "
-+              "TemplateTemplateParmDecl");
- 
- /// \brief Represents a class template specialization, which refers to
- /// a class template with a given set of template arguments.
---- tools/clang/include/clang/AST/EvaluatedExprVisitor.h	2014-12-03 13:00:20.000000000 -0800
-+++ tools/clang/include/clang/AST/EvaluatedExprVisitor.h	2015-07-17 16:43:46.487103645 -0700
-@@ -85,7 +85,7 @@
- 
-   void VisitLambdaExpr(LambdaExpr *LE) {
-     // Only visit the capture initializers, and not the body.
--    for (LambdaExpr::capture_init_iterator I = LE->capture_init_begin(),
-+    for (LambdaExpr::const_capture_init_iterator I = LE->capture_init_begin(),
-                                            E = LE->capture_init_end();
-          I != E; ++I)
-       if (*I)
---- tools/clang/include/clang/AST/Expr.h	2015-01-12 02:17:46.000000000 -0800
-+++ tools/clang/include/clang/AST/Expr.h	2015-07-17 16:43:46.491602160 -0700
-@@ -894,7 +894,7 @@
- ///   DeclRefExprBits.RefersToEnclosingVariableOrCapture
- ///       Specifies when this declaration reference expression (validly)
- ///       refers to an enclosed local or a captured variable.
--class DeclRefExpr : public Expr {
-+class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) DeclRefExpr : public Expr {
-   /// \brief The declaration that we are referencing.
-   ValueDecl *D;
- 
-@@ -1048,13 +1048,17 @@
-     if (!hasTemplateKWAndArgsInfo())
-       return nullptr;
- 
--    if (hasFoundDecl())
-+    if (hasFoundDecl()) {
-       return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(
--        &getInternalFoundDecl() + 1);
-+          llvm::alignAddr(&getInternalFoundDecl() + 1,
-+                          llvm::alignOf<ASTTemplateKWAndArgsInfo>()));
-+    }
- 
--    if (hasQualifier())
-+    if (hasQualifier()) {
-       return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(
--        &getInternalQualifierLoc() + 1);
-+          llvm::alignAddr(&getInternalQualifierLoc() + 1,
-+                          llvm::alignOf<ASTTemplateKWAndArgsInfo>()));
-+    }
- 
-     return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(this + 1);
-   }
-@@ -1167,6 +1171,16 @@
-   friend class ASTStmtReader;
-   friend class ASTStmtWriter;
- };
-+static_assert(llvm::AlignOf<DeclRefExpr>::Alignment >=
-+                  llvm::AlignOf<NestedNameSpecifierLoc>::Alignment,
-+              "Alignment is insufficient for objects appended to DeclRefExpr");
-+static_assert(llvm::AlignOf<NestedNameSpecifierLoc>::Alignment >=
-+                  llvm::AlignOf<NamedDecl *>::Alignment,
-+              "Alignment is insufficient for objects appended to DeclRefExpr");
-+// Code re-aligns before ASTTemplateKWAndArgsInfo
-+static_assert(llvm::AlignOf<DeclRefExpr>::Alignment >=
-+                  llvm::AlignOf<ASTTemplateKWAndArgsInfo>::Alignment,
-+              "Alignment is insufficient for objects appended to DeclRefExpr");
- 
- /// \brief [C99 6.4.2.2] - A predefined identifier such as __func__.
- class PredefinedExpr : public Expr {
-@@ -1968,6 +1982,12 @@
-     return child_range(begin, begin + NumExprs);
-   }
- };
-+static_assert(llvm::AlignOf<OffsetOfExpr>::Alignment >=
-+                  llvm::AlignOf<OffsetOfExpr::OffsetOfNode *>::Alignment,
-+              "Alignment is insufficient for objects appended to OffsetOfExpr");
-+static_assert(llvm::AlignOf<OffsetOfExpr::OffsetOfNode>::Alignment >=
-+                  llvm::AlignOf<Expr *>::Alignment,
-+              "Alignment is insufficient for objects appended to OffsetOfExpr");
- 
- /// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated)
- /// expression operand.  Used for sizeof/alignof (C99 6.5.3.4) and
-@@ -2309,9 +2329,10 @@
- 
- /// MemberExpr - [C99 6.5.2.3] Structure and Union Members.  X->F and X.F.
- ///
--class MemberExpr : public Expr {
-+class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) MemberExpr : public Expr {
-+public:
-   /// Extra data stored in some member expressions.
--  struct MemberNameQualifier {
-+  struct LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) MemberNameQualifier {
-     /// \brief The nested-name-specifier that qualifies the name, including
-     /// source-location information.
-     NestedNameSpecifierLoc QualifierLoc;
-@@ -2321,6 +2342,7 @@
-     DeclAccessPair FoundDecl;
-   };
- 
-+private:
-   /// Base - the expression for the base pointer or structure references.  In
-   /// X.F, this is "X".
-   Stmt *Base;
-@@ -2591,6 +2613,12 @@
-   friend class ASTReader;
-   friend class ASTStmtWriter;
- };
-+static_assert(llvm::AlignOf<MemberExpr>::Alignment >=
-+                  llvm::AlignOf<MemberExpr::MemberNameQualifier>::Alignment,
-+              "Alignment is insufficient for objects appended to MemberExpr");
-+static_assert(llvm::AlignOf<MemberExpr::MemberNameQualifier>::Alignment >=
-+                  llvm::AlignOf<ASTTemplateKWAndArgsInfo>::Alignment,
-+              "Alignment is insufficient for objects appended to MemberExpr");
- 
- /// CompoundLiteralExpr - [C99 6.5.2.5]
- ///
-@@ -2747,6 +2775,11 @@
-   // Iterators
-   child_range children() { return child_range(&Op, &Op+1); }
- };
-+static_assert(llvm::AlignOf<CastExpr>::Alignment >=
-+                  llvm::AlignOf<CXXBaseSpecifier *>::Alignment,
-+              "Alignment is insufficient for objects appended to CastExpr");
-+// (Note that the data is actually tacked onto one of its subclasses,
-+// but they'll inherit alignment)
- 
- /// ImplicitCastExpr - Allows us to explicitly represent implicit type
- /// conversions, which have no direct representation in the original
-@@ -4272,6 +4305,10 @@
-     return child_range(begin, begin + NumSubExprs);
-   }
- };
-+static_assert(
-+    llvm::AlignOf<DesignatedInitExpr>::Alignment >=
-+        llvm::AlignOf<Stmt *>::Alignment,
-+    "Alignment is insufficient for objects appended to DesignatedInitExpr");
- 
- /// \brief Represents an implicitly-generated value initialization of
- /// an object of a given type.
-@@ -4749,6 +4786,10 @@
-     return T->getStmtClass() == PseudoObjectExprClass;
-   }
- };
-+static_assert(
-+    llvm::AlignOf<PseudoObjectExpr>::Alignment >=
-+        llvm::AlignOf<Expr *>::Alignment,
-+    "Alignment is insufficient for objects appended to PseudoObjectExpr");
- 
- /// AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*,
- /// __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the
---- tools/clang/include/clang/AST/ExprCXX.h	2015-01-14 03:29:14.000000000 -0800
-+++ tools/clang/include/clang/AST/ExprCXX.h	2015-07-18 11:25:29.503136056 -0700
-@@ -933,6 +933,10 @@
-   friend class ASTStmtReader;
-   friend class ASTStmtWriter;
- };
-+static_assert(
-+    llvm::AlignOf<CXXDefaultArgExpr>::Alignment >=
-+        llvm::AlignOf<Expr *>::Alignment,
-+    "Alignment is insufficient for objects appended to CXXDefaultArgExpr");
- 
- /// \brief A use of a default initializer in a constructor or in aggregate
- /// initialization.
-@@ -1395,23 +1399,38 @@
-     getStoredStmts()[NumCaptures] = nullptr;
-   }
-   
--  Stmt **getStoredStmts() const {
-+  Stmt **getStoredStmts() {
-     return reinterpret_cast<Stmt **>(const_cast<LambdaExpr *>(this) + 1);
-   }
-   
-+  Stmt *const *getStoredStmts() const {
-+    return reinterpret_cast<Stmt *const *>(this + 1);
-+  }
-+  
-   /// \brief Retrieve the mapping from captures to the first array index
-   /// variable.
--  unsigned *getArrayIndexStarts() const {
-+  unsigned *getArrayIndexStarts() {
-     return reinterpret_cast<unsigned *>(getStoredStmts() + NumCaptures + 1);
-   }
-   
-+  const unsigned *getArrayIndexStarts() const {
-+    return reinterpret_cast<const unsigned *>(getStoredStmts() + NumCaptures + 1);
-+  }
-+  
-   /// \brief Retrieve the complete set of array-index variables.
--  VarDecl **getArrayIndexVars() const {
-+  VarDecl **getArrayIndexVars() {
-     unsigned ArrayIndexSize =
-         llvm::RoundUpToAlignment(sizeof(unsigned) * (NumCaptures + 1),
-                                  llvm::alignOf<VarDecl*>());
-     return reinterpret_cast<VarDecl **>(
--        reinterpret_cast<char*>(getArrayIndexStarts()) + ArrayIndexSize);
-+        reinterpret_cast<unsigned char*>(getArrayIndexStarts()) + ArrayIndexSize);
-+  }
-+
-+  VarDecl *const *getArrayIndexVars() const {
-+    unsigned ArrayIndexSize = llvm::RoundUpToAlignment(
-+        sizeof(unsigned) * (NumCaptures + 1), llvm::alignOf<VarDecl *>());
-+    return reinterpret_cast<VarDecl *const *>(
-+        reinterpret_cast<const unsigned char *>(getArrayIndexStarts()) + ArrayIndexSize);
-   }
- 
- public:
-@@ -1492,21 +1511,43 @@
-   /// arguments.
-   typedef Expr **capture_init_iterator;
- 
-+  /// \brief Const iterator that walks over the capture initialization
-+  /// arguments.
-+  typedef Expr *const *const_capture_init_iterator;
-+
-   /// \brief Retrieve the initialization expressions for this lambda's captures.
--  llvm::iterator_range<capture_init_iterator> capture_inits() const {
-+  llvm::iterator_range<capture_init_iterator> capture_inits() {
-     return llvm::iterator_range<capture_init_iterator>(capture_init_begin(),
-                                                        capture_init_end());
-   }
- 
-+  /// \brief Retrieve the initialization expressions for this lambda's captures.
-+  llvm::iterator_range<const_capture_init_iterator> capture_inits() const {
-+    return llvm::iterator_range<const_capture_init_iterator>(
-+        capture_init_begin(), capture_init_end());
-+  }
-+
-   /// \brief Retrieve the first initialization argument for this
-   /// lambda expression (which initializes the first capture field).
--  capture_init_iterator capture_init_begin() const {
-+  capture_init_iterator capture_init_begin() {
-     return reinterpret_cast<Expr **>(getStoredStmts());
-   }
- 
-+  /// \brief Retrieve the first initialization argument for this
-+  /// lambda expression (which initializes the first capture field).
-+  const_capture_init_iterator capture_init_begin() const {
-+    return reinterpret_cast<Expr *const *>(getStoredStmts());
-+  }
-+
-   /// \brief Retrieve the iterator pointing one past the last
-   /// initialization argument for this lambda expression.
--  capture_init_iterator capture_init_end() const {
-+  capture_init_iterator capture_init_end() {
-+    return capture_init_begin() + NumCaptures;
-+  }
-+
-+  /// \brief Retrieve the iterator pointing one past the last
-+  /// initialization argument for this lambda expression.
-+  const_capture_init_iterator capture_init_end() const {
-     return capture_init_begin() + NumCaptures;    
-   }
- 
-@@ -1515,7 +1556,8 @@
-   ///
-   /// \param Iter The iterator that points at the capture initializer for 
-   /// which we are extracting the corresponding index variables.
--  ArrayRef<VarDecl *> getCaptureInitIndexVars(capture_init_iterator Iter) const;
-+  ArrayRef<VarDecl *>
-+  getCaptureInitIndexVars(const_capture_init_iterator Iter) const;
-   
-   /// \brief Retrieve the source range covering the lambda introducer,
-   /// which contains the explicit capture list surrounded by square
-@@ -1570,6 +1612,16 @@
-   friend class ASTStmtReader;
-   friend class ASTStmtWriter;
- };
-+static_assert(llvm::AlignOf<LambdaExpr>::Alignment >=
-+                  llvm::AlignOf<Stmt *>::Alignment,
-+              "Alignment is insufficient for objects appended to LambdaExpr");
-+static_assert(llvm::AlignOf<Stmt *>::Alignment >=
-+                  llvm::AlignOf<unsigned>::Alignment,
-+              "Alignment is insufficient for objects appended to LambdaExpr");
-+// Code re-aligns before VarDecl *[]
-+static_assert(llvm::AlignOf<LambdaExpr>::Alignment >=
-+                  llvm::AlignOf<VarDecl *>::Alignment,
-+              "Alignment is insufficient for objects appended to LambdaExpr");
- 
- /// An expression "T()" which creates a value-initialized rvalue of type
- /// T, which is a non-class type.  See (C++98 [5.2.3p2]).
-@@ -2157,6 +2209,10 @@
-   friend class ASTStmtWriter;
- 
- };
-+static_assert(
-+    llvm::AlignOf<TypeTraitExpr>::Alignment >=
-+        llvm::AlignOf<TypeSourceInfo *>::Alignment,
-+    "Alignment is insufficient for objects appended to TypeTraitExpr");
- 
- /// \brief An Embarcadero array type trait, as used in the implementation of
- /// __array_rank and __array_extent.
-@@ -2289,7 +2345,7 @@
- 
- /// \brief A reference to an overloaded function set, either an
- /// \c UnresolvedLookupExpr or an \c UnresolvedMemberExpr.
--class OverloadExpr : public Expr {
-+class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) OverloadExpr : public Expr {
-   /// \brief The common name of these declarations.
-   DeclarationNameInfo NameInfo;
- 
-@@ -2578,6 +2634,10 @@
-     return T->getStmtClass() == UnresolvedLookupExprClass;
-   }
- };
-+static_assert(
-+    llvm::AlignOf<UnresolvedLookupExpr>::Alignment >=
-+        llvm::AlignOf<ASTTemplateKWAndArgsInfo>::Alignment,
-+    "Alignment is insufficient for objects appended to UnresolvedLookupExpr");
- 
- /// \brief A qualified reference to a name whose declaration cannot
- /// yet be resolved.
-@@ -2593,7 +2653,8 @@
- /// qualifier (X<T>::) and the name of the entity being referenced
- /// ("value"). Such expressions will instantiate to a DeclRefExpr once the
- /// declaration can be found.
--class DependentScopeDeclRefExpr : public Expr {
-+class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) DependentScopeDeclRefExpr
-+    : public Expr {
-   /// \brief The nested-name-specifier that qualifies this unresolved
-   /// declaration name.
-   NestedNameSpecifierLoc QualifierLoc;
-@@ -2739,6 +2800,10 @@
-   friend class ASTStmtReader;
-   friend class ASTStmtWriter;
- };
-+static_assert(llvm::AlignOf<DependentScopeDeclRefExpr>::Alignment >=
-+                  llvm::AlignOf<ASTTemplateKWAndArgsInfo>::Alignment,
-+              "Alignment is insufficient for objects appended to "
-+              "DependentScopeDeclRefExpr");
- 
- /// Represents an expression -- generally a full-expression -- that
- /// introduces cleanups to be run at the end of the sub-expression's
-@@ -2810,6 +2875,10 @@
-   // Iterators
-   child_range children() { return child_range(&SubExpr, &SubExpr + 1); }
- };
-+static_assert(
-+    llvm::AlignOf<ExprWithCleanups>::Alignment >=
-+        llvm::AlignOf<ExprWithCleanups::CleanupObject>::Alignment,
-+    "Alignment is insufficient for objects appended to ExprWithCleanups");
- 
- /// \brief Describes an explicit type conversion that uses functional
- /// notion but could not be resolved because one or more arguments are
-@@ -2930,6 +2999,10 @@
-     return child_range(begin, begin + NumArgs);
-   }
- };
-+static_assert(llvm::AlignOf<CXXUnresolvedConstructExpr>::Alignment >=
-+                  llvm::AlignOf<Expr *>::Alignment,
-+              "Alignment is insufficient for objects appended to "
-+              "CXXUnresolvedConstructExpr");
- 
- /// \brief Represents a C++ member access expression where the actual
- /// member referenced could not be resolved because the base
-@@ -2938,7 +3011,8 @@
- /// Like UnresolvedMemberExprs, these can be either implicit or
- /// explicit accesses.  It is only possible to get one of these with
- /// an implicit access if a qualifier is provided.
--class CXXDependentScopeMemberExpr : public Expr {
-+class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) CXXDependentScopeMemberExpr
-+    : public Expr {
-   /// \brief The expression for the base pointer or class reference,
-   /// e.g., the \c x in x.f.  Can be null in implicit accesses.
-   Stmt *Base;
-@@ -3177,6 +3251,10 @@
-   friend class ASTStmtReader;
-   friend class ASTStmtWriter;
- };
-+static_assert(llvm::AlignOf<CXXDependentScopeMemberExpr>::Alignment >=
-+                  llvm::AlignOf<ASTTemplateKWAndArgsInfo>::Alignment,
-+              "Alignment is insufficient for objects appended to "
-+              "CXXDependentScopeMemberExpr");
- 
- /// \brief Represents a C++ member access expression for which lookup
- /// produced a set of overloaded functions.
-@@ -3193,7 +3271,8 @@
- /// In the final AST, an explicit access always becomes a MemberExpr.
- /// An implicit access may become either a MemberExpr or a
- /// DeclRefExpr, depending on whether the member is static.
--class UnresolvedMemberExpr : public OverloadExpr {
-+class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) UnresolvedMemberExpr
-+    : public OverloadExpr {
-   /// \brief Whether this member expression used the '->' operator or
-   /// the '.' operator.
-   bool IsArrow : 1;
-@@ -3316,6 +3395,21 @@
-     return child_range(&Base, &Base + 1);
-   }
- };
-+static_assert(
-+    llvm::AlignOf<UnresolvedMemberExpr>::Alignment >=
-+        llvm::AlignOf<ASTTemplateKWAndArgsInfo>::Alignment,
-+    "Alignment is insufficient for objects appended to UnresolvedMemberExpr");
-+
-+inline ASTTemplateKWAndArgsInfo *OverloadExpr::getTemplateKWAndArgsInfo() {
-+  if (!HasTemplateKWAndArgsInfo)
-+    return nullptr;
-+  if (isa<UnresolvedLookupExpr>(this))
-+    return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(
-+        cast<UnresolvedLookupExpr>(this) + 1);
-+  else
-+    return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(
-+        cast<UnresolvedMemberExpr>(this) + 1);
-+}
- 
- /// \brief Represents a C++11 noexcept expression (C++ [expr.unary.noexcept]).
- ///
-@@ -3438,15 +3532,6 @@
-   }
- };
- 
--inline ASTTemplateKWAndArgsInfo *OverloadExpr::getTemplateKWAndArgsInfo() {
--  if (!HasTemplateKWAndArgsInfo) return nullptr;
--  if (isa<UnresolvedLookupExpr>(this))
--    return reinterpret_cast<ASTTemplateKWAndArgsInfo*>
--      (cast<UnresolvedLookupExpr>(this) + 1);
--  else
--    return reinterpret_cast<ASTTemplateKWAndArgsInfo*>
--      (cast<UnresolvedMemberExpr>(this) + 1);
--}
- 
- /// \brief Represents an expression that computes the length of a parameter
- /// pack.
-@@ -3709,6 +3794,10 @@
- 
-   child_range children() { return child_range(); }
- };
-+static_assert(
-+    llvm::AlignOf<FunctionParmPackExpr>::Alignment >=
-+        llvm::AlignOf<ParmVarDecl *>::Alignment,
-+    "Alignment is insufficient for objects appended to FunctionParmPackExpr");
- 
- /// \brief Represents a prvalue temporary that is written into memory so that
- /// a reference can bind to it.
---- tools/clang/include/clang/AST/ExprObjC.h	2014-12-18 09:13:56.000000000 -0800
-+++ tools/clang/include/clang/AST/ExprObjC.h	2015-07-17 16:43:46.499286743 -0700
-@@ -201,6 +201,10 @@
-     
-   friend class ASTStmtReader;
- };
-+static_assert(
-+    llvm::AlignOf<ObjCArrayLiteral>::Alignment >=
-+        llvm::AlignOf<Expr *>::Alignment,
-+    "Alignment is insufficient for objects appended to ObjCArrayLiteral");
- 
- /// \brief An element in an Objective-C dictionary literal.
- ///
-@@ -231,6 +235,7 @@
- /// ObjCDictionaryLiteral - AST node to represent objective-c dictionary 
- /// literals; as in:  @{@"name" : NSUserName(), @"date" : [NSDate date] };
- class ObjCDictionaryLiteral : public Expr {
-+public:
-   /// \brief Key/value pair used to store the key and value of a given element.
-   ///
-   /// Objects of this type are stored directly after the expression.
-@@ -251,6 +256,7 @@
-     unsigned NumExpansionsPlusOne;
-   };
- 
-+private:
-   /// \brief The number of elements in this dictionary literal.
-   unsigned NumElements : 31;
-   
-@@ -341,6 +347,7 @@
-   child_range children() { 
-     // Note: we're taking advantage of the layout of the KeyValuePair struct
-     // here. If that struct changes, this code will need to change as well.
-+    static_assert(sizeof(KeyValuePair) == sizeof(Stmt *) * 2, "");
-     return child_range(reinterpret_cast<Stmt **>(this + 1),
-                        reinterpret_cast<Stmt **>(this + 1) + NumElements * 2);
-   }
-@@ -348,7 +355,14 @@
-   friend class ASTStmtReader;
-   friend class ASTStmtWriter;
- };
--
-+static_assert(
-+    llvm::AlignOf<ObjCDictionaryLiteral>::Alignment >=
-+        llvm::AlignOf<ObjCDictionaryLiteral::KeyValuePair>::Alignment,
-+    "Alignment is insufficient for objects appended to ObjCDictionaryLiteral");
-+static_assert(
-+    llvm::AlignOf<ObjCDictionaryLiteral::KeyValuePair>::Alignment >=
-+        llvm::AlignOf<ObjCDictionaryLiteral::ExpansionData>::Alignment,
-+    "Alignment is insufficient for objects appended to ObjCDictionaryLiteral");
- 
- /// ObjCEncodeExpr, used for \@encode in Objective-C.  \@encode has the same
- /// type and behavior as StringLiteral except that the string initializer is
-@@ -1394,6 +1408,17 @@
-   friend class ASTStmtReader;
-   friend class ASTStmtWriter;
- };
-+static_assert(
-+    llvm::AlignOf<ObjCMessageExpr>::Alignment >=
-+        llvm::AlignOf<void *>::Alignment,
-+    "Alignment is insufficient for objects appended to ObjCMessageExpr");
-+static_assert(
-+    llvm::AlignOf<void *>::Alignment >= llvm::AlignOf<Expr *>::Alignment,
-+    "Alignment is insufficient for objects appended to ObjCMessageExpr");
-+static_assert(
-+    llvm::AlignOf<Expr *>::Alignment >=
-+        llvm::AlignOf<SourceLocation>::Alignment,
-+    "Alignment is insufficient for objects appended to ObjCMessageExpr");
- 
- /// ObjCIsaExpr - Represent X->isa and X.isa when X is an ObjC 'id' type.
- /// (similar in spirit to MemberExpr).
---- tools/clang/include/clang/AST/Stmt.h	2015-01-12 02:17:46.000000000 -0800
-+++ tools/clang/include/clang/AST/Stmt.h	2015-07-17 16:43:46.502138721 -0700
-@@ -865,7 +865,10 @@
-     return T->getStmtClass() == AttributedStmtClass;
-   }
- };
--
-+static_assert(
-+    llvm::AlignOf<AttributedStmt>::Alignment >=
-+        llvm::AlignOf<Attr *>::Alignment,
-+    "Alignment is insufficient for objects appended to AttributedStmt");
- 
- /// IfStmt - This represents an if/then/else.
- ///
-@@ -2070,8 +2073,10 @@
-   /// \brief Construct an empty captured statement.
-   CapturedStmt(EmptyShell Empty, unsigned NumCaptures);
- 
--  Stmt **getStoredStmts() const {
--    return reinterpret_cast<Stmt **>(const_cast<CapturedStmt *>(this) + 1);
-+  Stmt **getStoredStmts() { return reinterpret_cast<Stmt **>(this + 1); }
-+
-+  Stmt *const *getStoredStmts() const {
-+    return reinterpret_cast<Stmt *const *>(this + 1);
-   }
- 
-   Capture *getStoredCaptures() const;
-@@ -2090,14 +2095,12 @@
- 
-   /// \brief Retrieve the statement being captured.
-   Stmt *getCapturedStmt() { return getStoredStmts()[NumCaptures]; }
--  const Stmt *getCapturedStmt() const {
--    return const_cast<CapturedStmt *>(this)->getCapturedStmt();
--  }
-+  const Stmt *getCapturedStmt() const { return getStoredStmts()[NumCaptures]; }
- 
-   /// \brief Retrieve the outlined function declaration.
-   CapturedDecl *getCapturedDecl() { return CapDeclAndKind.getPointer(); }
-   const CapturedDecl *getCapturedDecl() const {
--    return const_cast<CapturedStmt *>(this)->getCapturedDecl();
-+    return CapDeclAndKind.getPointer();
-   }
- 
-   /// \brief Set the outlined function declaration.
-@@ -2158,18 +2161,36 @@
-   typedef Expr **capture_init_iterator;
-   typedef llvm::iterator_range<capture_init_iterator> capture_init_range;
- 
--  capture_init_range capture_inits() const {
-+  /// \brief Const iterator that walks over the capture initialization
-+  /// arguments.
-+  typedef Expr *const *const_capture_init_iterator;
-+  typedef llvm::iterator_range<const_capture_init_iterator>
-+      const_capture_init_range;
-+
-+  capture_init_range capture_inits() {
-     return capture_init_range(capture_init_begin(), capture_init_end());
-   }
- 
-+  const_capture_init_range capture_inits() const {
-+    return const_capture_init_range(capture_init_begin(), capture_init_end());
-+  }
-+
-   /// \brief Retrieve the first initialization argument.
--  capture_init_iterator capture_init_begin() const {
-+  capture_init_iterator capture_init_begin() {
-     return reinterpret_cast<Expr **>(getStoredStmts());
-   }
- 
-+  const_capture_init_iterator capture_init_begin() const {
-+    return reinterpret_cast<Expr *const *>(getStoredStmts());
-+  }
-+
-   /// \brief Retrieve the iterator pointing one past the last initialization
-   /// argument.
--  capture_init_iterator capture_init_end() const {
-+  capture_init_iterator capture_init_end() {
-+    return capture_init_begin() + NumCaptures;
-+  }
-+
-+  const_capture_init_iterator capture_init_end() const {
-     return capture_init_begin() + NumCaptures;
-   }
- 
-@@ -2191,6 +2212,13 @@
- 
-   friend class ASTStmtReader;
- };
-+static_assert(llvm::AlignOf<CapturedStmt>::Alignment >=
-+                  llvm::AlignOf<Stmt *>::Alignment,
-+              "Alignment is insufficient for objects appended to CapturedStmt");
-+// Code re-aligns before Capture[]
-+static_assert(llvm::AlignOf<CapturedStmt>::Alignment >=
-+                  llvm::AlignOf<CapturedStmt::Capture>::Alignment,
-+              "Alignment is insufficient for objects appended to CapturedStmt");
- 
- }  // end namespace clang
- 
---- tools/clang/include/clang/AST/StmtCXX.h	2014-05-05 23:48:52.000000000 -0700
-+++ tools/clang/include/clang/AST/StmtCXX.h	2015-07-17 16:43:46.503758907 -0700
-@@ -118,6 +118,9 @@
- 
-   friend class ASTStmtReader;
- };
-+static_assert(llvm::AlignOf<CXXTryStmt>::Alignment >=
-+                  llvm::AlignOf<Stmt *>::Alignment,
-+              "Alignment is insufficient for objects appended to CXXTryStmt");
- 
- /// CXXForRangeStmt - This represents C++0x [stmt.ranged]'s ranged for
- /// statement, represented as 'for (range-declarator : range-expression)'.
---- tools/clang/include/clang/AST/StmtObjC.h	2014-05-05 23:48:52.000000000 -0700
-+++ tools/clang/include/clang/AST/StmtObjC.h	2015-07-17 16:43:46.505254168 -0700
-@@ -249,6 +249,9 @@
-                        getStmts() + 1 + NumCatchStmts + HasFinally);
-   }
- };
-+static_assert(
-+    llvm::AlignOf<ObjCAtTryStmt>::Alignment >= llvm::AlignOf<Stmt *>::Alignment,
-+    "Alignment is insufficient for objects appended to ObjCAtTryStmt");
- 
- /// \brief Represents Objective-C's \@synchronized statement.
- ///
---- tools/clang/include/clang/AST/TemplateBase.h	2015-01-14 03:29:14.000000000 -0800
-+++ tools/clang/include/clang/AST/TemplateBase.h	2015-07-17 16:43:46.506876445 -0700
-@@ -360,6 +360,20 @@
-   void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) const;
- };
- 
-+static_assert(llvm::AlignOf<TemplateSpecializationType>::Alignment >=
-+                  llvm::AlignOf<TemplateArgument>::Alignment,
-+              "Alignment is insufficient for objects appended to "
-+              "TemplateSpecializationType");
-+static_assert(llvm::AlignOf<TemplateArgument>::Alignment >=
-+                  llvm::AlignOf<QualType>::Alignment,
-+              "Alignment is insufficient for objects appended to "
-+              "TemplateSpecializationType");
-+
-+static_assert(llvm::AlignOf<DependentTemplateSpecializationType>::Alignment >=
-+                  llvm::AlignOf<TemplateArgument>::Alignment,
-+              "Alignment is insufficient for objects appended to "
-+              "DependentTemplateSpecializationType");
-+
- /// Location information for a TemplateArgument.
- struct TemplateArgumentLocInfo {
- private:
-@@ -604,6 +618,10 @@
-   void copyInto(TemplateArgumentListInfo &List) const;
-   static std::size_t sizeFor(unsigned NumTemplateArgs);
- };
-+static_assert(llvm::AlignOf<ASTTemplateArgumentListInfo>::Alignment >=
-+                  llvm::AlignOf<TemplateArgumentLoc>::Alignment,
-+              "Alignment is insufficient for objects appended to "
-+              "ASTTemplateArgumentListInfo");
- 
- /// \brief Extends ASTTemplateArgumentListInfo with the source location
- /// information for the template keyword; this is used as part of the
-@@ -640,6 +658,18 @@
- 
-   static std::size_t sizeFor(unsigned NumTemplateArgs);
- };
-+static_assert(llvm::AlignOf<ASTTemplateKWAndArgsInfo>::Alignment >=
-+                  llvm::AlignOf<TemplateArgumentLoc>::Alignment,
-+              "Alignment is insufficient for objects appended to "
-+              "ASTTemplateKWAndArgsInfo");
-+static_assert(llvm::AlignOf<ASTTemplateKWAndArgsInfo>::Alignment >=
-+                  llvm::AlignOf<SourceLocation>::Alignment,
-+              "Alignment is insufficient for objects appended to "
-+              "ASTTemplateKWAndArgsInfo");
-+static_assert(llvm::AlignOf<TemplateArgumentLoc>::Alignment >=
-+                  llvm::AlignOf<SourceLocation>::Alignment,
-+              "Alignment is insufficient for objects appended to "
-+              "ASTTemplateKWAndArgsInfo");
- 
- const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
-                                     const TemplateArgument &Arg);
---- tools/clang/include/clang/AST/TemplateName.h	2014-05-10 13:57:56.000000000 -0700
-+++ tools/clang/include/clang/AST/TemplateName.h	2015-07-17 16:43:46.508333537 -0700
-@@ -108,6 +108,10 @@
-   iterator begin() const { return getStorage(); }
-   iterator end() const { return getStorage() + size(); }
- };
-+static_assert(llvm::AlignOf<OverloadedTemplateStorage>::Alignment >=
-+                  llvm::AlignOf<NamedDecl *>::Alignment,
-+              "Alignment is insufficient for objects appended to "
-+              "OverloadedTemplateStorage");
- 
- /// \brief A structure for storing an already-substituted template template
- /// parameter pack.
---- tools/clang/include/clang/AST/Type.h	2015-01-14 03:29:14.000000000 -0800
-+++ tools/clang/include/clang/AST/Type.h	2015-07-17 16:43:46.512517865 -0700
-@@ -2991,11 +2991,13 @@
-     assert(hasAnyConsumedParams());
- 
-     // Find the end of the exceptions.
--    Expr *const *eh_end = reinterpret_cast<Expr *const *>(param_type_end());
--    if (getExceptionSpecType() != EST_ComputedNoexcept)
--      eh_end += NumExceptions;
--    else
-+    Expr *const *eh_end = reinterpret_cast<Expr *const *>(exception_end());
-+    if (getExceptionSpecType() == EST_ComputedNoexcept)
-       eh_end += 1; // NoexceptExpr
-+    // The memory layout of these types isn't handled here, so
-+    // hopefully this is never called for them?
-+    assert(getExceptionSpecType() != EST_Uninstantiated &&
-+           getExceptionSpecType() != EST_Unevaluated);
- 
-     return reinterpret_cast<const bool*>(eh_end);
-   }
-@@ -3167,7 +3169,29 @@
-                       param_type_iterator ArgTys, unsigned NumArgs,
-                       const ExtProtoInfo &EPI, const ASTContext &Context);
- };
--
-+static_assert(
-+    llvm::AlignOf<FunctionProtoType>::Alignment >=
-+        llvm::AlignOf<QualType>::Alignment,
-+    "Alignment is insufficient for objects appended to FunctionProtoType");
-+// After QualType[], there can be one of 4 options: more QualType, Expr*, 2x
-+// FunctionDecl*, FunctionDecl*
-+static_assert(
-+    llvm::AlignOf<QualType>::Alignment >= llvm::AlignOf<Expr *>::Alignment,
-+    "Alignment is insufficient for objects appended to FunctionProtoType");
-+static_assert(
-+    llvm::AlignOf<QualType>::Alignment >=
-+        llvm::AlignOf<FunctionDecl *>::Alignment,
-+    "Alignment is insufficient for objects appended to FunctionProtoType");
-+// And then, after any of those options, comes bool[]
-+static_assert(
-+    llvm::AlignOf<QualType>::Alignment >= llvm::AlignOf<bool>::Alignment,
-+    "Alignment is insufficient for objects appended to FunctionProtoType");
-+static_assert(
-+    llvm::AlignOf<Expr *>::Alignment >= llvm::AlignOf<bool>::Alignment,
-+    "Alignment is insufficient for objects appended to FunctionProtoType");
-+static_assert(
-+    llvm::AlignOf<FunctionDecl *>::Alignment >= llvm::AlignOf<bool>::Alignment,
-+    "Alignment is insufficient for objects appended to FunctionProtoType");
- 
- /// \brief Represents the dependent type named by a dependently-scoped
- /// typename using declaration, e.g.
-@@ -3777,8 +3801,9 @@
- /// TemplateArguments, followed by a QualType representing the
- /// non-canonical aliased type when the template is a type alias
- /// template.
--class TemplateSpecializationType
--  : public Type, public llvm::FoldingSetNode {
-+class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) TemplateSpecializationType
-+    : public Type,
-+      public llvm::FoldingSetNode {
-   /// \brief The name of the template being specialized.  This is
-   /// either a TemplateName::Template (in which case it is a
-   /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a
-@@ -3900,6 +3925,13 @@
-     return T->getTypeClass() == TemplateSpecialization;
-   }
- };
-+// static_assert(llvm::AlignOf<TemplateSpecializationType>::Alignment >=
-+// llvm::AlignOf<TemplateArgument>::Alignment, "Alignment is insufficient for
-+// objects appended to TemplateSpecializationType");
-+// static_assert(llvm::AlignOf<TemplateArgument>::Alignment >=
-+// llvm::AlignOf<QualType>::Alignment, "Alignment is insufficient for objects
-+// appended to TemplateSpecializationType");
-+// ^ Moved after class TemplateArgument, as it is is forward declared here.
- 
- /// \brief The injected class name of a C++ class template or class
- /// template partial specialization.  Used to record that a type was
-@@ -4175,8 +4207,9 @@
- /// DependentTemplateSpecializationType - Represents a template
- /// specialization type whose template cannot be resolved, e.g.
- ///   A<T>::template B<T>
--class DependentTemplateSpecializationType :
--  public TypeWithKeyword, public llvm::FoldingSetNode {
-+class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) DependentTemplateSpecializationType
-+    : public TypeWithKeyword,
-+      public llvm::FoldingSetNode {
- 
-   /// \brief The nested name specifier containing the qualifier.
-   NestedNameSpecifier *NNS;
-@@ -4241,6 +4274,10 @@
-     return T->getTypeClass() == DependentTemplateSpecialization;
-   }
- };
-+// static_assert(llvm::AlignOf<DependentTemplateSpecializationType>::Alignment
-+// >= llvm::AlignOf<TemplateArgument>::Alignment, "Alignment is insufficient for
-+// objects appended to DependentTemplateSpecializationType");
-+// ^ Moved after class TemplateArgument, as it is is forward declared here.
- 
- /// \brief Represents a pack expansion of types.
- ///
-@@ -4456,6 +4493,10 @@
-                       ObjCProtocolDecl *const *protocols,
-                       unsigned NumProtocols);
- };
-+static_assert(
-+    llvm::AlignOf<ObjCObjectTypeImpl>::Alignment >=
-+        llvm::AlignOf<ObjCProtocolDecl *>::Alignment,
-+    "Alignment is insufficient for objects appended to ObjCObjectTypeImpl");
- 
- inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorage() {
-   return reinterpret_cast<ObjCProtocolDecl**>(
---- tools/clang/include/clang/AST/TypeLoc.h	2014-10-24 06:52:55.000000000 -0700
-+++ tools/clang/include/clang/AST/TypeLoc.h	2015-07-17 16:43:46.514327822 -0700
-@@ -199,6 +199,7 @@
- 
- /// \brief Return the TypeLoc for a type source info.
- inline TypeLoc TypeSourceInfo::getTypeLoc() const {
-+  // TODO: is this alignment already sufficient?
-   return TypeLoc(Ty, const_cast<void*>(static_cast<const void*>(this + 1)));
- }
- 
---- tools/clang/include/clang/CodeGen/CGFunctionInfo.h	2014-12-12 15:41:25.000000000 -0800
-+++ tools/clang/include/clang/CodeGen/CGFunctionInfo.h	2015-07-17 16:43:46.515714903 -0700
-@@ -333,11 +333,13 @@
- /// CGFunctionInfo - Class to encapsulate the information about a
- /// function definition.
- class CGFunctionInfo : public llvm::FoldingSetNode {
-+public:
-   struct ArgInfo {
-     CanQualType type;
-     ABIArgInfo info;
-   };
- 
-+private:
-   /// The LLVM::CallingConv to use for this function (as specified by the
-   /// user).
-   unsigned CallingConvention : 8;
-@@ -500,6 +502,10 @@
-     }
-   }
- };
-+static_assert(
-+    llvm::AlignOf<CGFunctionInfo>::Alignment >=
-+        llvm::AlignOf<CGFunctionInfo::ArgInfo>::Alignment,
-+    "Alignment is insufficient for objects appended to CGFunctionInfo");
- 
- }  // end namespace CodeGen
- }  // end namespace clang
---- tools/clang/include/clang/Lex/MacroArgs.h	2014-08-13 12:25:19.000000000 -0400
-+++ tools/clang/include/clang/Lex/MacroArgs.h	2015-07-17 22:23:39.000000000 -0400
-@@ -15,13 +15,13 @@
- #define LLVM_CLANG_LEX_MACROARGS_H
- 
- #include "clang/Basic/LLVM.h"
-+#include "clang/Lex/Token.h"
- #include "llvm/ADT/ArrayRef.h"
- #include <vector>
- 
- namespace clang {
-   class MacroInfo;
-   class Preprocessor;
--  class Token;
-   class SourceLocation;
- 
- /// MacroArgs - An instance of this class captures information about
-@@ -120,6 +120,9 @@
-   /// its freelist.
-   MacroArgs *deallocate();
- };
-+static_assert(llvm::AlignOf<MacroArgs>::Alignment >=
-+                  llvm::AlignOf<Token>::Alignment,
-+              "Alignment is insufficient for objects appended to MacroArgs");
- 
- }  // end namespace clang
- 
---- tools/clang/include/clang/Lex/MacroInfo.h	2014-08-13 12:25:19.000000000 -0400
-+++ tools/clang/include/clang/Lex/MacroInfo.h	2015-07-18 01:52:39.590867365 -0400
-@@ -17,11 +17,15 @@
- 
- #include "clang/Lex/Token.h"
- #include "llvm/ADT/ArrayRef.h"
-+#include "llvm/ADT/FoldingSet.h"
-+#include "llvm/ADT/PointerIntPair.h"
- #include "llvm/ADT/SmallVector.h"
- #include "llvm/Support/Allocator.h"
- #include <cassert>
- 
- namespace clang {
-+class Module;
-+class ModuleMacro;
- class Preprocessor;
- 
- /// \brief Encapsulates the data about a macro definition (e.g. its tokens).
-@@ -294,6 +298,9 @@
- 
-   friend class Preprocessor;
- };
-+static_assert(llvm::AlignOf<MacroInfo>::Alignment >=
-+                  llvm::AlignOf<unsigned>::Alignment,
-+              "Alignment is insufficient for objects appended to MacroInfo");
- 
- class DefMacroDirective;
- 
-@@ -517,6 +524,75 @@
-   static bool classof(const DefMacroDirective *) { return true; }
- };
- 
-+/// \brief Represents a macro directive exported by a module.
-+///
-+/// There's an instance of this class for every macro #define or #undef that is
-+/// the final directive for a macro name within a module. These entities also
-+/// represent the macro override graph.
-+///
-+/// These are stored in a FoldingSet in the preprocessor.
-+class ModuleMacro : public llvm::FoldingSetNode {
-+  /// The name defined by the macro.
-+  IdentifierInfo *II;
-+  /// The body of the #define, or nullptr if this is a #undef.
-+  MacroInfo *Macro;
-+  /// The module that exports this macro.
-+  Module *OwningModule;
-+  /// The number of module macros that override this one.
-+  unsigned NumOverriddenBy;
-+  /// The number of modules whose macros are directly overridden by this one.
-+  unsigned NumOverrides;
-+  // ModuleMacro *OverriddenMacros[NumOverrides];
-+
-+  friend class Preprocessor;
-+
-+  ModuleMacro(Module *OwningModule, IdentifierInfo *II, MacroInfo *Macro,
-+              ArrayRef<ModuleMacro *> Overrides)
-+      : II(II), Macro(Macro), OwningModule(OwningModule), NumOverriddenBy(0),
-+        NumOverrides(Overrides.size()) {
-+    std::copy(Overrides.begin(), Overrides.end(),
-+              reinterpret_cast<ModuleMacro **>(this + 1));
-+  }
-+
-+public:
-+  static ModuleMacro *create(Preprocessor &PP, Module *OwningModule,
-+                             IdentifierInfo *II, MacroInfo *Macro,
-+                             ArrayRef<ModuleMacro *> Overrides);
-+
-+  void Profile(llvm::FoldingSetNodeID &ID) const {
-+    return Profile(ID, OwningModule, II);
-+  }
-+  static void Profile(llvm::FoldingSetNodeID &ID, Module *OwningModule,
-+                      IdentifierInfo *II) {
-+    ID.AddPointer(OwningModule);
-+    ID.AddPointer(II);
-+  }
-+
-+  /// Get the ID of the module that exports this macro.
-+  Module *getOwningModule() const { return OwningModule; }
-+
-+  /// Get definition for this exported #define, or nullptr if this
-+  /// represents a #undef.
-+  MacroInfo *getMacroInfo() const { return Macro; }
-+
-+  /// Iterators over the overridden module IDs.
-+  /// \{
-+  typedef ModuleMacro *const *overrides_iterator;
-+  overrides_iterator overrides_begin() const {
-+    return reinterpret_cast<overrides_iterator>(this + 1);
-+  }
-+  overrides_iterator overrides_end() const {
-+    return overrides_begin() + NumOverrides;
-+  }
-+  ArrayRef<ModuleMacro *> overrides() const {
-+    return llvm::makeArrayRef(overrides_begin(), overrides_end());
-+  }
-+  /// \}
-+
-+  /// Get the number of macros that override this one.
-+  unsigned getNumOverridingMacros() const { return NumOverriddenBy; }
-+};
-+
- /// \brief A directive for an undefined macro.
- class UndefMacroDirective : public MacroDirective  {
- public:
-@@ -550,6 +626,9 @@
-   }
-   static bool classof(const VisibilityMacroDirective *) { return true; }
- };
-+static_assert(llvm::AlignOf<ModuleMacro>::Alignment >=
-+                  llvm::AlignOf<ModuleMacro *>::Alignment,
-+              "Alignment is insufficient for objects appended to ModuleMacro");
- 
- inline unsigned *MacroDirective::getModuleDataStart() {
-   if (auto *Def = dyn_cast<DefMacroDirective>(this))
---- tools/clang/include/clang/Sema/AttributeList.h	2015-01-20 11:27:49.000000000 -0800
-+++ tools/clang/include/clang/Sema/AttributeList.h	2015-07-17 16:43:46.520539511 -0700
-@@ -135,9 +135,7 @@
-   AttributeList *NextInPool;
- 
-   /// Arguments, if any, are stored immediately following the object.
--  ArgsUnion *getArgsBuffer() {
--    return reinterpret_cast<ArgsUnion*>(this+1);
--  }
-+  ArgsUnion *getArgsBuffer() { return reinterpret_cast<ArgsUnion *>(this + 1); }
-   ArgsUnion const *getArgsBuffer() const {
-     return reinterpret_cast<ArgsUnion const *>(this+1);
-   }
-@@ -468,6 +466,26 @@
-   /// a Spelling enumeration, the value UINT_MAX is returned.
-   unsigned getSemanticSpelling() const;
- };
-+static_assert(
-+    llvm::AlignOf<AttributeList>::Alignment >=
-+        llvm::AlignOf<ArgsUnion>::Alignment,
-+    "Alignment is insufficient for objects appended to AttributeList");
-+static_assert(
-+    llvm::AlignOf<ArgsUnion>::Alignment >=
-+        llvm::AlignOf<AvailabilityChange>::Alignment,
-+    "Alignment is insufficient for objects appended to AttributeList");
-+static_assert(
-+    llvm::AlignOf<ArgsUnion>::Alignment >=
-+        llvm::AlignOf<AttributeList::TypeTagForDatatypeData>::Alignment,
-+    "Alignment is insufficient for objects appended to AttributeList");
-+static_assert(
-+    llvm::AlignOf<AttributeList>::Alignment >=
-+        llvm::AlignOf<ParsedType>::Alignment,
-+    "Alignment is insufficient for objects appended to AttributeList");
-+static_assert(
-+    llvm::AlignOf<AttributeList>::Alignment >=
-+        llvm::AlignOf<AttributeList::PropertyData>::Alignment,
-+    "Alignment is insufficient for objects appended to AttributeList");
- 
- /// A factory, from which one makes pools, from which one creates
- /// individual attributes which are deallocated with the pool.
---- tools/clang/include/clang/Sema/CodeCompleteConsumer.h	2014-05-05 23:48:52.000000000 -0700
-+++ tools/clang/include/clang/Sema/CodeCompleteConsumer.h	2015-07-17 16:43:46.522097320 -0700
-@@ -493,6 +493,14 @@
-   /// which is mainly useful for debugging.
-   std::string getAsString() const;
- };
-+static_assert(
-+    llvm::AlignOf<CodeCompletionString>::Alignment >=
-+        llvm::AlignOf<CodeCompletionString::Chunk>::Alignment,
-+    "Alignment is insufficient for objects appended to CodeCompletionString");
-+static_assert(
-+    llvm::AlignOf<CodeCompletionString::Chunk>::Alignment >=
-+        llvm::AlignOf<const char *>::Alignment,
-+    "Alignment is insufficient for objects appended to CodeCompletionString");
- 
- /// \brief An allocator used specifically for the purpose of code completion.
- class CodeCompletionAllocator : public llvm::BumpPtrAllocator {
---- tools/clang/include/clang/Sema/ParsedTemplate.h	2014-05-05 23:48:52.000000000 -0700
-+++ tools/clang/include/clang/Sema/ParsedTemplate.h	2015-07-17 16:43:46.523177530 -0700
-@@ -205,6 +205,10 @@
-       free(this); 
-     }
-   };
-+  static_assert(
-+      llvm::AlignOf<TemplateIdAnnotation>::Alignment >=
-+          llvm::AlignOf<ParsedTemplateArgument>::Alignment,
-+      "Alignment is insufficient for objects appended to TemplateIdAnnotation");
- 
-   /// Retrieves the range of the given template parameter lists.
-   SourceRange getTemplateParamsRange(TemplateParameterList const *const *Params,
---- tools/clang/lib/AST/Decl.cpp	2015-05-04 11:23:59.000000000 -0700
-+++ tools/clang/lib/AST/Decl.cpp	2015-07-17 16:43:46.525788978 -0700
-@@ -3064,8 +3064,8 @@
-                              const TemplateArgumentListInfo &TemplateArgs) {
-   assert(TemplateOrSpecialization.isNull());
-   size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
--  Size += Templates.size() * sizeof(FunctionTemplateDecl*);
-   Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
-+  Size += Templates.size() * sizeof(FunctionTemplateDecl *);
-   void *Buffer = Context.Allocate(Size);
-   DependentFunctionTemplateSpecializationInfo *Info =
-     new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
-@@ -3078,8 +3078,8 @@
-                                       const TemplateArgumentListInfo &TArgs)
-   : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
- 
--  d.NumTemplates = Ts.size();
--  d.NumArgs = TArgs.size();
-+  NumTemplates = Ts.size();
-+  NumArgs = TArgs.size();
- 
-   FunctionTemplateDecl **TsArray =
-     const_cast<FunctionTemplateDecl**>(getTemplates());
---- tools/clang/lib/AST/DeclBase.cpp	2014-11-17 15:36:45.000000000 -0800
-+++ tools/clang/lib/AST/DeclBase.cpp	2015-07-17 17:03:06.999226816 -0700
-@@ -45,14 +45,28 @@
-   getASTContext().getExternalSource()->updateOutOfDateIdentifier(II);
- }
- 
-+#define DECL(DERIVED, BASE)                                                    \
-+  static_assert(llvm::AlignOf<uint64_t>::Alignment >=                          \
-+                    llvm::AlignOf<DERIVED##Decl>::Alignment,                   \
-+                "Alignment is insufficient for objects appended to all Decl "  \
-+                "subclasses");
-+#define ABSTRACT_DECL(DECL)
-+#include "clang/AST/DeclNodes.inc"
-+
- void *Decl::operator new(std::size_t Size, const ASTContext &Context,
-                          unsigned ID, std::size_t Extra) {
-   // Allocate an extra 8 bytes worth of storage, which ensures that the
-   // resulting pointer will still be 8-byte aligned. 
--  void *Start = Context.Allocate(Size + Extra + 8);
--  void *Result = (char*)Start + 8;
-+  static_assert(sizeof(unsigned) * 2 >= llvm::AlignOf<uint64_t>::Alignment,
-+      "sizeof(unsigned) * 2 < llvm::AlignOf<uint64_t>::Alignment!");
-+
-+  void *Start = Context.Allocate(Size + Extra + 8, 8U);
-+  void *Result = reinterpret_cast<void*>(
-+      reinterpret_cast<unsigned char*>(
-+        reinterpret_cast<unsigned char*>(Start) + 8));
- 
--  unsigned *PrefixPtr = (unsigned *)Result - 2;
-+  unsigned *PrefixPtr =
-+    reinterpret_cast<unsigned*>(reinterpret_cast<unsigned*>(Result) - 2);
- 
-   // Zero out the first 4 bytes; this is used to store the owning module ID.
-   PrefixPtr[0] = 0;
---- tools/clang/lib/AST/Expr.cpp	2015-01-12 02:17:46.000000000 -0800
-+++ tools/clang/lib/AST/Expr.cpp	2015-07-17 16:43:46.530620842 -0700
-@@ -399,10 +399,15 @@
-     Size += sizeof(NestedNameSpecifierLoc);
-   if (FoundD)
-     Size += sizeof(NamedDecl *);
--  if (TemplateArgs)
-+  if (TemplateArgs) {
-+    Size = llvm::RoundUpToAlignment(Size,
-+                                    llvm::alignOf<ASTTemplateKWAndArgsInfo>());
-     Size += ASTTemplateKWAndArgsInfo::sizeFor(TemplateArgs->size());
--  else if (TemplateKWLoc.isValid())
-+  } else if (TemplateKWLoc.isValid()) {
-+    Size = llvm::RoundUpToAlignment(Size,
-+                                    llvm::alignOf<ASTTemplateKWAndArgsInfo>());
-     Size += ASTTemplateKWAndArgsInfo::sizeFor(0);
-+  }
- 
-   void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>());
-   return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,
-@@ -420,8 +425,11 @@
-     Size += sizeof(NestedNameSpecifierLoc);
-   if (HasFoundDecl)
-     Size += sizeof(NamedDecl *);
--  if (HasTemplateKWAndArgsInfo)
-+  if (HasTemplateKWAndArgsInfo) {
-+    Size = llvm::RoundUpToAlignment(Size,
-+                                    llvm::alignOf<ASTTemplateKWAndArgsInfo>());
-     Size += ASTTemplateKWAndArgsInfo::sizeFor(NumTemplateArgs);
-+  }
- 
-   void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>());
-   return new (Mem) DeclRefExpr(EmptyShell());
-@@ -3871,7 +3879,8 @@
-                            SourceLocation ColonOrEqualLoc,
-                            bool UsesColonSyntax, Expr *Init) {
-   void *Mem = C.Allocate(sizeof(DesignatedInitExpr) +
--                         sizeof(Stmt *) * (IndexExprs.size() + 1), 8);
-+                             sizeof(Stmt *) * (IndexExprs.size() + 1),
-+                         llvm::alignOf<DesignatedInitExpr>());
-   return new (Mem) DesignatedInitExpr(C, C.VoidTy, NumDesignators, Designators,
-                                       ColonOrEqualLoc, UsesColonSyntax,
-                                       IndexExprs, Init);
---- tools/clang/lib/AST/ExprCXX.cpp	2014-09-25 17:28:20.000000000 -0700
-+++ tools/clang/lib/AST/ExprCXX.cpp	2015-07-17 16:43:46.532400798 -0700
-@@ -1070,14 +1070,14 @@
- }
- 
- ArrayRef<VarDecl *> 
--LambdaExpr::getCaptureInitIndexVars(capture_init_iterator Iter) const {
-+LambdaExpr::getCaptureInitIndexVars(const_capture_init_iterator Iter) const {
-   assert(HasArrayIndexVars && "No array index-var data?");
-   
-   unsigned Index = Iter - capture_init_begin();
-   assert(Index < getLambdaClass()->getLambdaData().NumCaptures &&
-          "Capture index out-of-range");
--  VarDecl **IndexVars = getArrayIndexVars();
--  unsigned *IndexStarts = getArrayIndexStarts();
-+  VarDecl *const *IndexVars = getArrayIndexVars();
-+  const unsigned *IndexStarts = getArrayIndexStarts();
-   return llvm::makeArrayRef(IndexVars + IndexStarts[Index],
-                             IndexVars + IndexStarts[Index + 1]);
- }
-@@ -1098,8 +1098,12 @@
- }
- 
- CompoundStmt *LambdaExpr::getBody() const {
-+  // FIXME: this mutation in getBody is bogus. It should be
-+  // initialized in ASTStmtReader::VisitLambdaExpr, but for reasons I
-+  // don't understand, that doesn't work.
-   if (!getStoredStmts()[NumCaptures])
--    getStoredStmts()[NumCaptures] = getCallOperator()->getBody();
-+    *const_cast<clang::Stmt **>(&getStoredStmts()[NumCaptures]) =
-+        getCallOperator()->getBody();
-     
-   return reinterpret_cast<CompoundStmt *>(getStoredStmts()[NumCaptures]);
- }
---- tools/clang/lib/AST/Stmt.cpp	2014-12-14 23:07:06.000000000 -0800
-+++ tools/clang/lib/AST/Stmt.cpp	2015-07-17 16:43:46.536947418 -0700
-@@ -816,7 +816,7 @@
- CXXTryStmt *CXXTryStmt::Create(const ASTContext &C, SourceLocation tryLoc,
-                                Stmt *tryBlock, ArrayRef<Stmt*> handlers) {
-   std::size_t Size = sizeof(CXXTryStmt);
--  Size += ((handlers.size() + 1) * sizeof(Stmt));
-+  Size += ((handlers.size() + 1) * sizeof(Stmt *));
- 
-   void *Mem = C.Allocate(Size, llvm::alignOf<CXXTryStmt>());
-   return new (Mem) CXXTryStmt(tryLoc, tryBlock, handlers);
-@@ -825,7 +825,7 @@
- CXXTryStmt *CXXTryStmt::Create(const ASTContext &C, EmptyShell Empty,
-                                unsigned numHandlers) {
-   std::size_t Size = sizeof(CXXTryStmt);
--  Size += ((numHandlers + 1) * sizeof(Stmt));
-+  Size += ((numHandlers + 1) * sizeof(Stmt *));
- 
-   void *Mem = C.Allocate(Size, llvm::alignOf<CXXTryStmt>());
-   return new (Mem) CXXTryStmt(Empty, numHandlers);
-@@ -2027,4 +2027,3 @@
-       C.Allocate(Size + sizeof(OMPClause *) * NumClauses + sizeof(Stmt *));
-   return new (Mem) OMPTeamsDirective(NumClauses);
- }
--
---- tools/clang/lib/Basic/IdentifierTable.cpp	2014-12-11 04:18:08.000000000 -0800
-+++ tools/clang/lib/Basic/IdentifierTable.cpp	2015-07-17 16:43:46.538457921 -0700
-@@ -376,6 +376,11 @@
-     Profile(ID, keyword_begin(), getNumArgs());
-   }
- };
-+static_assert(
-+    llvm::AlignOf<MultiKeywordSelector>::Alignment >=
-+        llvm::AlignOf<IdentifierInfo *>::Alignment,
-+    "Alignment is insufficient for objects appended to MultiKeywordSelector");
-+
- } // end namespace clang.
- 
- unsigned Selector::getNumArgs() const {
---- tools/clang/lib/CodeGen/CGCleanup.h	2014-11-18 23:49:47.000000000 -0800
-+++ tools/clang/lib/CodeGen/CGCleanup.h	2015-07-17 16:43:46.540112662 -0700
-@@ -211,9 +211,12 @@
-     return Scope->getKind() == Catch;
-   }
- };
-+static_assert(llvm::AlignOf<EHCatchScope>::Alignment >=
-+                  llvm::AlignOf<EHCatchScope::Handler *>::Alignment,
-+              "Alignment is insufficient for objects appended to EHCatchScope");
- 
- /// A cleanup scope which generates the cleanup blocks lazily.
--class EHCleanupScope : public EHScope {
-+class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) EHCleanupScope : public EHScope {
-   /// The nearest normal cleanup scope enclosing this one.
-   EHScopeStack::stable_iterator EnclosingNormal;
- 
-@@ -391,6 +394,13 @@
-     return (Scope->getKind() == Cleanup);
-   }
- };
-+// Assert objects tacked on the end of EHCleanupScope won't be
-+// misaligned.  NOTE: there's actually a bunch of different data
-+// classes tacked on, so let's just ensure alignment good enough for
-+// uint64_t bytes.
-+static_assert(llvm::AlignOf<EHCleanupScope>::Alignment >=
-+                  llvm::AlignOf<uint64_t>::Alignment,
-+              "");
- 
- /// An exceptions scope which filters exceptions thrown through it.
- /// Only exceptions matching the filter types will be permitted to be
-@@ -435,6 +445,10 @@
-     return scope->getKind() == Filter;
-   }
- };
-+static_assert(
-+    llvm::AlignOf<EHFilterScope>::Alignment >=
-+        llvm::AlignOf<llvm::Value *>::Alignment,
-+    "Alignment is insufficient for objects appended to EHFilterScope");
- 
- /// An exceptions scope which calls std::terminate if any exception
- /// reaches it.
-@@ -467,27 +481,27 @@
-   EHScope &operator*() const { return *get(); }
- 
-   iterator &operator++() {
-+    size_t Size;
-     switch (get()->getKind()) {
-     case EHScope::Catch:
--      Ptr += EHCatchScope::getSizeForNumHandlers(
-+      Size = EHCatchScope::getSizeForNumHandlers(
-           static_cast<const EHCatchScope*>(get())->getNumHandlers());
-       break;
- 
-     case EHScope::Filter:
--      Ptr += EHFilterScope::getSizeForNumFilters(
-+      Size = EHFilterScope::getSizeForNumFilters(
-           static_cast<const EHFilterScope*>(get())->getNumFilters());
-       break;
- 
-     case EHScope::Cleanup:
--      Ptr += static_cast<const EHCleanupScope*>(get())
--        ->getAllocatedSize();
-+      Size = static_cast<const EHCleanupScope *>(get())->getAllocatedSize();
-       break;
- 
-     case EHScope::Terminate:
--      Ptr += EHTerminateScope::getSize();
-+      Size = EHTerminateScope::getSize();
-       break;
-     }
--
-+    Ptr += llvm::RoundUpToAlignment(Size, ScopeStackAlignment);
-     return *this;
-   }
- 
-@@ -523,7 +537,7 @@
- 
-   EHCatchScope &scope = cast<EHCatchScope>(*begin());
-   InnermostEHScope = scope.getEnclosingEHScope();
--  StartOfData += EHCatchScope::getSizeForNumHandlers(scope.getNumHandlers());
-+  unallocate(EHCatchScope::getSizeForNumHandlers(scope.getNumHandlers()));
- }
- 
- inline void EHScopeStack::popTerminate() {
-@@ -531,7 +545,7 @@
- 
-   EHTerminateScope &scope = cast<EHTerminateScope>(*begin());
-   InnermostEHScope = scope.getEnclosingEHScope();
--  StartOfData += EHTerminateScope::getSize();
-+  unallocate(EHTerminateScope::getSize());
- }
- 
- inline EHScopeStack::iterator EHScopeStack::find(stable_iterator sp) const {
---- tools/clang/lib/CodeGen/CGCleanup.cpp	2015-01-13 23:38:27.000000000 -0800
-+++ tools/clang/lib/CodeGen/CGCleanup.cpp	2015-07-17 17:08:23.853121118 -0700
-@@ -94,6 +94,7 @@
- 
- /// Push an entry of the given size onto this protected-scope stack.
- char *EHScopeStack::allocate(size_t Size) {
-+  Size = llvm::RoundUpToAlignment(Size, ScopeStackAlignment);
-   if (!StartOfBuffer) {
-     unsigned Capacity = 1024;
-     while (Capacity < Size) Capacity *= 2;
-@@ -123,6 +124,10 @@
-   return StartOfData;
- }
- 
-+void EHScopeStack::unallocate(size_t Size) {
-+  StartOfData += llvm::RoundUpToAlignment(Size, ScopeStackAlignment);
-+}
-+
- EHScopeStack::stable_iterator
- EHScopeStack::getInnermostActiveNormalCleanup() const {
-   for (stable_iterator si = getInnermostNormalCleanup(), se = stable_end();
-@@ -153,7 +158,6 @@
- 
- 
- void *EHScopeStack::pushCleanup(CleanupKind Kind, size_t Size) {
--  assert(((Size % sizeof(void*)) == 0) && "cleanup type is misaligned");
-   char *Buffer = allocate(EHCleanupScope::getSizeForCleanupSize(Size));
-   bool IsNormalCleanup = Kind & NormalCleanup;
-   bool IsEHCleanup = Kind & EHCleanup;
-@@ -181,7 +185,7 @@
-   EHCleanupScope &Cleanup = cast<EHCleanupScope>(*begin());
-   InnermostNormalCleanup = Cleanup.getEnclosingNormalCleanup();
-   InnermostEHScope = Cleanup.getEnclosingEHScope();
--  StartOfData += Cleanup.getAllocatedSize();
-+  unallocate(Cleanup.getAllocatedSize());
- 
-   // Destroy the cleanup.
-   Cleanup.Destroy();
-@@ -211,7 +215,7 @@
-   assert(!empty() && "popping exception stack when not empty");
- 
-   EHFilterScope &filter = cast<EHFilterScope>(*begin());
--  StartOfData += EHFilterScope::getSizeForNumFilters(filter.getNumFilters());
-+  unallocate(EHFilterScope::getSizeForNumFilters(filter.getNumFilters()));
- 
-   InnermostEHScope = filter.getEnclosingEHScope();
- }
---- tools/clang/lib/CodeGen/CGExprCXX.cpp	2015-01-13 23:38:27.000000000 -0800
-+++ tools/clang/lib/CodeGen/CGExprCXX.cpp	2015-07-17 16:43:46.544527492 -0700
-@@ -1129,6 +1129,10 @@
-       EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
-     }
-   };
-+  static_assert(
-+      llvm::AlignOf<CallDeleteDuringNew>::Alignment >=
-+          llvm::AlignOf<RValue>::Alignment,
-+      "Alignment is insufficient for objects appended to CallDeleteDuringNew");
- 
-   /// A cleanup to call the given 'operator delete' function upon
-   /// abnormal exit from a new expression when the new expression is
-@@ -1188,6 +1192,10 @@
-       EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
-     }
-   };
-+  static_assert(
-+      llvm::AlignOf<CallDeleteDuringConditionalNew>::Alignment >=
-+          llvm::AlignOf<DominatingValue<RValue>::saved_type>::Alignment,
-+      "Alignment is insufficient for objects appended to CallDeleteDuringNew");
- }
- 
- /// Enter a cleanup to call 'operator delete' if the initializer in a
-@@ -1819,7 +1827,7 @@
-       MakeAddrLValue(Slot.getAddr(), E->getType(), Slot.getAlignment());
- 
-   CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
--  for (LambdaExpr::capture_init_iterator i = E->capture_init_begin(),
-+  for (LambdaExpr::const_capture_init_iterator i = E->capture_init_begin(),
-                                          e = E->capture_init_end();
-        i != e; ++i, ++CurField) {
-     // Emit initialization
---- tools/clang/lib/CodeGen/CGStmt.cpp	2015-01-13 23:38:27.000000000 -0800
-+++ tools/clang/lib/CodeGen/CGStmt.cpp	2015-07-17 16:43:46.546244580 -0700
-@@ -2122,7 +2122,7 @@
-       CreateMemTemp(RecordTy, "agg.captured"), RecordTy);
- 
-   RecordDecl::field_iterator CurField = RD->field_begin();
--  for (CapturedStmt::capture_init_iterator I = S.capture_init_begin(),
-+  for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
-                                            E = S.capture_init_end();
-        I != E; ++I, ++CurField) {
-     LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
---- tools/clang/lib/CodeGen/EHScopeStack.h	2014-10-31 19:33:56.000000000 -0400
-+++ tools/clang/lib/CodeGen/EHScopeStack.h	2015-07-18 01:53:43.588447919 -0400
-@@ -89,6 +89,8 @@
- /// and catch blocks.
- class EHScopeStack {
- public:
-+  enum { ScopeStackAlignment = llvm::AlignOf<uint64_t>::Alignment };
-+
-   /// A saved depth on the scope stack.  This is necessary because
-   /// pushing scopes onto the stack invalidates iterators.
-   class stable_iterator {
-@@ -297,6 +299,7 @@
-   SmallVector<BranchFixup, 8> BranchFixups;
- 
-   char *allocate(size_t Size);
-+  void unallocate(size_t Size);
- 
-   void *pushCleanup(CleanupKind K, size_t DataSize);
- 
-@@ -311,6 +314,8 @@
-   /// Push a lazily-created cleanup on the stack.
-   template <class T>
-   void pushCleanup(CleanupKind Kind) {
-+    static_assert(llvm::AlignOf<T>::Alignment <= ScopeStackAlignment,
-+        "Insufficient Alignment!");
-     void *Buffer = pushCleanup(Kind, sizeof(T));
-     Cleanup *Obj = new(Buffer) T();
-     (void) Obj;
-@@ -319,6 +324,8 @@
-   /// Push a lazily-created cleanup on the stack.
-   template <class T, class A0>
-   void pushCleanup(CleanupKind Kind, A0 a0) {
-+    static_assert(llvm::AlignOf<T>::Alignment <= ScopeStackAlignment,
-+        "Insufficient Alignment!");
-     void *Buffer = pushCleanup(Kind, sizeof(T));
-     Cleanup *Obj = new(Buffer) T(a0);
-     (void) Obj;
-@@ -327,6 +334,8 @@
-   /// Push a lazily-created cleanup on the stack.
-   template <class T, class A0, class A1>
-   void pushCleanup(CleanupKind Kind, A0 a0, A1 a1) {
-+    static_assert(llvm::AlignOf<T>::Alignment <= ScopeStackAlignment,
-+        "Insufficient Alignment!");
-     void *Buffer = pushCleanup(Kind, sizeof(T));
-     Cleanup *Obj = new(Buffer) T(a0, a1);
-     (void) Obj;
-@@ -335,6 +344,8 @@
-   /// Push a lazily-created cleanup on the stack.
-   template <class T, class A0, class A1, class A2>
-   void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2) {
-+    static_assert(llvm::AlignOf<T>::Alignment <= ScopeStackAlignment,
-+        "Insufficient Alignment!");
-     void *Buffer = pushCleanup(Kind, sizeof(T));
-     Cleanup *Obj = new(Buffer) T(a0, a1, a2);
-     (void) Obj;
-@@ -343,6 +354,8 @@
-   /// Push a lazily-created cleanup on the stack.
-   template <class T, class A0, class A1, class A2, class A3>
-   void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2, A3 a3) {
-+    static_assert(llvm::AlignOf<T>::Alignment <= ScopeStackAlignment,
-+        "Insufficient Alignment!");
-     void *Buffer = pushCleanup(Kind, sizeof(T));
-     Cleanup *Obj = new(Buffer) T(a0, a1, a2, a3);
-     (void) Obj;
-@@ -351,11 +364,24 @@
-   /// Push a lazily-created cleanup on the stack.
-   template <class T, class A0, class A1, class A2, class A3, class A4>
-   void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) {
-+    static_assert(llvm::AlignOf<T>::Alignment <= ScopeStackAlignment,
-+        "Insufficient Alignment!");
-     void *Buffer = pushCleanup(Kind, sizeof(T));
-     Cleanup *Obj = new(Buffer) T(a0, a1, a2, a3, a4);
-     (void) Obj;
-   }
- 
-+  /// Push a lazily-created cleanup on the stack. Tuple version.
-+  template <class T, class... As>
-+  void pushCleanupTuple(CleanupKind Kind, std::tuple<As...> A) {
-+    static_assert(llvm::AlignOf<T>::Alignment <= ScopeStackAlignment,
-+        "Insufficient Alignment!");
-+    void *Buffer = pushCleanup(Kind, sizeof(T));
-+    Cleanup *Obj = new (Buffer) T(std::move(A));
-+    (void) Obj;
-+  }
-+
-+
-   // Feel free to add more variants of the following:
- 
-   /// Push a cleanup with non-constant storage requirements on the
-@@ -371,6 +397,8 @@
-   /// stack is modified.
-   template <class T, class A0, class A1, class A2>
-   T *pushCleanupWithExtra(CleanupKind Kind, size_t N, A0 a0, A1 a1, A2 a2) {
-+    static_assert(llvm::AlignOf<T>::Alignment <= ScopeStackAlignment,
-+        "Insufficient Alignment!");
-     void *Buffer = pushCleanup(Kind, sizeof(T) + T::getExtraSize(N));
-     return new (Buffer) T(N, a0, a1, a2);
-   }
---- tools/clang/lib/Lex/PPDirectives.cpp	2014-12-27 23:42:49.000000000 -0800
-+++ tools/clang/lib/Lex/PPDirectives.cpp	2015-07-17 16:43:46.550148988 -0700
-@@ -48,8 +48,6 @@
- 
- MacroInfo *Preprocessor::AllocateDeserializedMacroInfo(SourceLocation L,
-                                                        unsigned SubModuleID) {
--  static_assert(llvm::AlignOf<MacroInfo>::Alignment >= sizeof(SubModuleID),
--                "alignment for MacroInfo is less than the ID");
-   DeserializedMacroInfoChain *MIChain =
-       BP.Allocate<DeserializedMacroInfoChain>();
-   MIChain->Next = DeserialMIChainHead;
---- tools/clang/lib/Sema/SemaExceptionSpec.cpp	2014-11-21 19:09:05.000000000 -0800
-+++ tools/clang/lib/Sema/SemaExceptionSpec.cpp	2015-07-17 16:43:46.552022232 -0700
-@@ -971,7 +971,8 @@
-   case Expr::LambdaExprClass: {
-     const LambdaExpr *Lambda = cast<LambdaExpr>(E);
-     CanThrowResult CT = CT_Cannot;
--    for (LambdaExpr::capture_init_iterator Cap = Lambda->capture_init_begin(),
-+    for (LambdaExpr::const_capture_init_iterator
-+             Cap = Lambda->capture_init_begin(),
-                                         CapEnd = Lambda->capture_init_end();
-          Cap != CapEnd; ++Cap)
-       CT = mergeCanThrow(CT, canThrow(*Cap));
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/006-solaris-LLVM-libLLVMAnalysis.patch	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,118 @@
+# 22902339 memory corruption caused by undefined behavior in LLVM IR Module
+# Miscellaneous cleanup fixes.
+# Replace SmallVectorImpl | SmallVector with std::vector.
+# 3.9.X upstream.
+--- include/llvm/Analysis/BlockFrequencyInfoImpl.h	2015-12-18 12:53:24.000000000 -0900
++++ include/llvm/Analysis/BlockFrequencyInfoImpl.h	2016-07-07 10:08:31.067332185 -0800
+@@ -249,7 +249,9 @@
+     LoopData *Loop; ///< The loop this block is inside.
+     BlockMass Mass; ///< Mass distribution from the entry block.
+ 
+-    WorkingData(const BlockNode &Node) : Node(Node), Loop(nullptr) {}
++    WorkingData() : Node(), Loop(nullptr), Mass() { }
++    WorkingData(const BlockNode &Node) : Node(Node), Loop(nullptr), Mass() { }
++    ~WorkingData() { }
+ 
+     bool isLoopHeader() const { return Loop && Loop->isHeader(Node); }
+     bool isDoubleLoopHeader() const {
+@@ -332,9 +334,10 @@
+     DistType Type;
+     BlockNode TargetNode;
+     uint64_t Amount;
+-    Weight() : Type(Local), Amount(0) {}
++    Weight() : Type(Local), TargetNode(), Amount(0ULL) { }
+     Weight(DistType Type, BlockNode TargetNode, uint64_t Amount)
+-        : Type(Type), TargetNode(TargetNode), Amount(Amount) {}
++    : Type(Type), TargetNode(TargetNode), Amount(Amount) { }
++    ~Weight() { }
+   };
+ 
+   /// \brief Distribution of unscaled probability weight.
+@@ -985,7 +988,9 @@
+ 
+ template <class BT> void BlockFrequencyInfoImpl<BT>::initializeRPOT() {
+   const BlockT *Entry = &F->front();
+-  RPOT.reserve(F->size());
++  if (F->size())
++    RPOT.reserve(F->size());
++
+   std::copy(po_begin(Entry), po_end(Entry), std::back_inserter(RPOT));
+   std::reverse(RPOT.begin(), RPOT.end());
+ 
+@@ -999,7 +1004,9 @@
+     Nodes[*I] = Node;
+   }
+ 
+-  Working.reserve(RPOT.size());
++  if (RPOT.size())
++    Working.reserve(RPOT.size());
++
+   for (size_t Index = 0; Index < RPOT.size(); ++Index)
+     Working.emplace_back(Index);
+   Freqs.resize(RPOT.size());
+
+###
+--- lib/Analysis/LazyCallGraph.cpp	2015-12-27 20:54:20.000000000 -0500
++++ lib/Analysis/LazyCallGraph.cpp	2016-05-28 13:36:41.670887743 -0400
+@@ -234,7 +234,7 @@
+   ConnectedSCCs.insert(&CallerC);
+ 
+   // We build up a DFS stack of the parents chains.
+-  SmallVector<std::pair<SCC *, SCC::parent_iterator>, 8> DFSSCCs;
++  std::vector<std::pair<SCC *, SCC::parent_iterator> > DFSSCCs;
+   SmallPtrSet<SCC *, 8> VisitedSCCs;
+   int ConnectedDepth = -1;
+   SCC *C = this;
+@@ -265,7 +265,7 @@
+     // If we've found a connection anywhere below this point on the stack (and
+     // thus up the parent graph from the caller), the current node needs to be
+     // added to the connected set now that we've processed all of its parents.
+-    if ((int)DFSSCCs.size() == ConnectedDepth) {
++    if (static_cast<int>(DFSSCCs.size()) == ConnectedDepth) {
+       --ConnectedDepth; // We're finished with this connection.
+       ConnectedSCCs.insert(C);
+     } else {
+@@ -279,8 +279,9 @@
+       break; // We've walked all the parents of the caller transitively.
+ 
+     // Pop off the prior node and position to unwind the depth first recursion.
+-    std::tie(C, I) = DFSSCCs.pop_back_val();
++    std::tie(C, I) = DFSSCCs.back();
+     E = C->parent_end();
++    DFSSCCs.pop_back();
+   }
+ 
+   // Now that we have identified all of the SCCs which need to be merged into
+###
+--- lib/Analysis/CFG.cpp	2015-11-20 15:02:06.000000000 -0800
++++ lib/Analysis/CFG.cpp	2016-05-24 19:44:24.894893025 -0700
+@@ -19,6 +19,8 @@
+ 
+ using namespace llvm;
+ 
++#include <vector>
++
+ /// FindFunctionBackedges - Analyze the specified function to find all of the
+ /// loop backedges in the function and return them.  This is a relatively cheap
+ /// (compared to computing dominators and loop info) analysis.
+@@ -31,7 +33,7 @@
+     return;
+ 
+   SmallPtrSet<const BasicBlock*, 8> Visited;
+-  SmallVector<std::pair<const BasicBlock*, succ_const_iterator>, 8> VisitStack;
++  std::vector<std::pair<const BasicBlock*, succ_const_iterator> > VisitStack;
+   SmallPtrSet<const BasicBlock*, 8> InStack;
+ 
+   Visited.insert(BB);
+@@ -60,7 +62,10 @@
+       VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
+     } else {
+       // Go up one level.
+-      InStack.erase(VisitStack.pop_back_val().first);
++      std::pair<const BasicBlock*, succ_const_iterator> &Back =
++        VisitStack.back();
++      InStack.erase(Back.first);
++      VisitStack.pop_back();
+     }
+   } while (!VisitStack.empty());
+ }
--- a/components/llvm/patches/007-TemplateBase.patch	Thu Jul 28 16:15:45 2016 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,224 +0,0 @@
-# 1. RAII - Resource Acquisition Is Initialization.
-# 2. Default bit-copying or assigning union member bitfields
-#    between unions of different types or size is undefined behavior.
-# 3. Default bit-copying or assigning unions of different types or
-#    size is undefined behavior.
-# 4. Default bit-copying or assigning nested unions is undefined behavior.
-# https://llvm.org/bugs/show_bug.cgi?id=24608
---- tools/clang/include/clang/AST/TemplateBase.h	2015-07-17 16:43:46.506876445 -0700
-+++ tools/clang/include/clang/AST/TemplateBase.h	2015-07-17 17:39:04.239131360 -0700
-@@ -22,6 +22,7 @@
- #include "llvm/ADT/iterator_range.h"
- #include "llvm/Support/Compiler.h"
- #include "llvm/Support/ErrorHandling.h"
-+#include <cstring>
- 
- namespace llvm {
-   class FoldingSetNodeID;
-@@ -84,8 +85,8 @@
-     // We store a decomposed APSInt with the data allocated by ASTContext if
-     // BitWidth > 64. The memory may be shared between multiple
-     // TemplateArgument instances.
--    unsigned BitWidth : 31;
--    unsigned IsUnsigned : 1;
-+    unsigned BitWidth;
-+    bool IsUnsigned;
-     union {
-       uint64_t VAL;          ///< Used to store the <= 64 bits integer value.
-       const uint64_t *pVal;  ///< Used to store the >64 bits integer value.
-@@ -112,6 +113,7 @@
-     struct A Args;
-     struct TA TemplateArg;
-     struct TV TypeOrValue;
-+    uint64_t Buffer[8];
-   };
- 
-   TemplateArgument(TemplateName, bool) LLVM_DELETED_FUNCTION;
-@@ -119,12 +121,27 @@
- public:
-   /// \brief Construct an empty, invalid template argument.
-   TemplateArgument() {
-+    (void) std::memset(Buffer, 0, sizeof(Buffer));
-     TypeOrValue.Kind = Null;
-     TypeOrValue.V = 0;
-   }
- 
-+  TemplateArgument(const TemplateArgument &RHS) {
-+    (void) std::memset(Buffer, 0, sizeof(Buffer));
-+    (void) std::memcpy(Buffer, RHS.Buffer, sizeof(Buffer));
-+  }
-+
-+  TemplateArgument &operator=(const TemplateArgument &RHS) {
-+    if (this != &RHS) {
-+      (void) std::memset(Buffer, 0, sizeof(Buffer));
-+      (void) std::memcpy(Buffer, RHS.Buffer, sizeof(Buffer));
-+    }
-+    return *this;
-+  }
-+
-   /// \brief Construct a template type argument.
-   TemplateArgument(QualType T, bool isNullPtr = false) {
-+    (void) std::memset(Buffer, 0, sizeof(Buffer));
-     TypeOrValue.Kind = isNullPtr ? NullPtr : Type;
-     TypeOrValue.V = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
-   }
-@@ -134,6 +151,7 @@
-   /// template declaration.
-   TemplateArgument(ValueDecl *D, QualType QT) {
-     assert(D && "Expected decl");
-+    (void) std::memset(Buffer, 0, sizeof(Buffer));
-     DeclArg.Kind = Declaration;
-     DeclArg.QT = QT.getAsOpaquePtr();
-     DeclArg.D = D;
-@@ -146,6 +164,7 @@
-   /// \brief Construct an integral constant template argument with the same
-   /// value as Other but a different type.
-   TemplateArgument(const TemplateArgument &Other, QualType Type) {
-+    (void) std::memset(Buffer, 0, sizeof(Buffer));
-     Integer = Other.Integer;
-     Integer.Type = Type.getAsOpaquePtr();
-   }
-@@ -159,6 +178,7 @@
-   ///
-   /// \param Name The template name.
-   TemplateArgument(TemplateName Name) {
-+    (void) std::memset(Buffer, 0, sizeof(Buffer));
-     TemplateArg.Kind = Template;
-     TemplateArg.Name = Name.getAsVoidPointer();
-     TemplateArg.NumExpansions = 0;
-@@ -176,6 +196,7 @@
-   /// \param NumExpansions The number of expansions that will be generated by
-   /// instantiating
-   TemplateArgument(TemplateName Name, Optional<unsigned> NumExpansions) {
-+    (void) std::memset(Buffer, 0, sizeof(Buffer));
-     TemplateArg.Kind = TemplateExpansion;
-     TemplateArg.Name = Name.getAsVoidPointer();
-     if (NumExpansions)
-@@ -190,6 +211,7 @@
-   /// lists used for dependent types and for expression; it will not
-   /// occur in a non-dependent, canonical template argument list.
-   TemplateArgument(Expr *E) {
-+    (void) std::memset(Buffer, 0, sizeof(Buffer));
-     TypeOrValue.Kind = Expression;
-     TypeOrValue.V = reinterpret_cast<uintptr_t>(E);
-   }
-@@ -199,6 +221,7 @@
-   /// We assume that storage for the template arguments provided
-   /// outlives the TemplateArgument itself.
-   TemplateArgument(const TemplateArgument *Args, unsigned NumArgs) {
-+    (void) std::memset(Buffer, 0, sizeof(Buffer));
-     this->Args.Kind = Pack;
-     this->Args.Args = Args;
-     this->Args.NumArgs = NumArgs;
-@@ -391,25 +414,55 @@
-     struct T Template;
-     Expr *Expression;
-     TypeSourceInfo *Declarator;
-+    unsigned long Buffer[4];
-   };
- 
- public:
-   TemplateArgumentLocInfo();
-   
--  TemplateArgumentLocInfo(TypeSourceInfo *TInfo) : Declarator(TInfo) {}
-+  TemplateArgumentLocInfo(TypeSourceInfo *TInfo) {
-+    (void) std::memset(Buffer, 0, sizeof(Buffer));
-+    Declarator = TInfo;
-+  }
-   
--  TemplateArgumentLocInfo(Expr *E) : Expression(E) {}
-+  TemplateArgumentLocInfo(Expr *E) {
-+    (void) std::memset(Buffer, 0, sizeof(Buffer));
-+    Expression = E;
-+  }
-   
-   TemplateArgumentLocInfo(NestedNameSpecifierLoc QualifierLoc,
-                           SourceLocation TemplateNameLoc,
--                          SourceLocation EllipsisLoc)
--  {
-+                          SourceLocation EllipsisLoc) {
-+    (void) std::memset(Buffer, 0, sizeof(Buffer));
-     Template.Qualifier = QualifierLoc.getNestedNameSpecifier();
-     Template.QualifierLocData = QualifierLoc.getOpaqueData();
-     Template.TemplateNameLoc = TemplateNameLoc.getRawEncoding();
-     Template.EllipsisLoc = EllipsisLoc.getRawEncoding();
-   }
- 
-+  TemplateArgumentLocInfo(const TemplateArgumentLocInfo &RHS) {
-+    (void) std::memset(Buffer, 0, sizeof(Buffer));
-+    Template.Qualifier = RHS.Template.Qualifier;
-+    Template.QualifierLocData = RHS.Template.QualifierLocData;
-+    Template.TemplateNameLoc = RHS.Template.TemplateNameLoc;
-+    Template.EllipsisLoc = RHS.Template.EllipsisLoc;
-+    Expression = RHS.Expression;
-+    Declarator = RHS.Declarator;
-+  }
-+
-+  TemplateArgumentLocInfo &operator=(const TemplateArgumentLocInfo &RHS) {
-+    if (this != &RHS) {
-+      (void) std::memset(Buffer, 0, sizeof(Buffer));
-+      Template.Qualifier = RHS.Template.Qualifier;
-+      Template.QualifierLocData = RHS.Template.QualifierLocData;
-+      Template.TemplateNameLoc = RHS.Template.TemplateNameLoc;
-+      Template.EllipsisLoc = RHS.Template.EllipsisLoc;
-+      Expression = RHS.Expression;
-+      Declarator = RHS.Declarator;
-+    }
-+    return *this;
-+  }
-+
-   TypeSourceInfo *getAsTypeSourceInfo() const {
-     return Declarator;
-   }
-# 1. RAII - Resource Acquisition Is Initialization.
-# 2. Allocate memory with suitable alignment for uint64_t.
-# 3. reinterpret_cast<> from void* to <type*>.
---- tools/clang/lib/AST/TemplateBase.cpp	2015-01-08 16:58:16.000000000 -0800
-+++ tools/clang/lib/AST/TemplateBase.cpp	2015-07-17 17:42:51.744142395 -0700
-@@ -71,6 +71,7 @@
- 
- TemplateArgument::TemplateArgument(ASTContext &Ctx, const llvm::APSInt &Value,
-                                    QualType Type) {
-+  (void) std::memset(Buffer, '\0', sizeof(Buffer));
-   Integer.Kind = Integral;
-   // Copy the APSInt value into our decomposed form.
-   Integer.BitWidth = Value.getBitWidth();
-@@ -78,9 +79,9 @@
-   // If the value is large, we have to get additional memory from the ASTContext
-   unsigned NumWords = Value.getNumWords();
-   if (NumWords > 1) {
--    void *Mem = Ctx.Allocate(NumWords * sizeof(uint64_t));
--    std::memcpy(Mem, Value.getRawData(), NumWords * sizeof(uint64_t));
--    Integer.pVal = static_cast<uint64_t *>(Mem);
-+    void *Mem = Ctx.Allocate(NumWords * sizeof(uint64_t), alignof(uint64_t));
-+    (void) std::memcpy(Mem, Value.getRawData(), NumWords * sizeof(uint64_t));
-+    Integer.pVal = reinterpret_cast<uint64_t *>(Mem);
-   } else {
-     Integer.VAL = Value.getZExtValue();
-   }
-@@ -422,7 +423,9 @@
- //===----------------------------------------------------------------------===//
- 
- TemplateArgumentLocInfo::TemplateArgumentLocInfo() {
--  memset((void*)this, 0, sizeof(TemplateArgumentLocInfo));
-+  (void) std::memset(Buffer, 0, sizeof(Buffer));
-+  Expression = nullptr;
-+  Declarator = nullptr;
- }
- 
- SourceRange TemplateArgumentLoc::getSourceRange() const {
-# 1. Pointer Arithmetic Paranoia.
---- tools/clang/lib/AST/Type.cpp	2014-12-28 01:18:54.000000000 -0800
-+++ tools/clang/lib/AST/Type.cpp	2015-07-17 17:43:57.848813992 -0700
-@@ -1464,7 +1464,10 @@
-     if (Args[I].containsUnexpandedParameterPack())
-       setContainsUnexpandedParameterPack();
- 
--    new (&getArgBuffer()[I]) TemplateArgument(Args[I]);
-+    TemplateArgument *TA = getArgBuffer();
-+    TA = &(TA[I]);
-+    TA = new (TA) TemplateArgument();
-+    *TA = Args[I];
-   }
- }
- 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/007-solaris-LLVM-libLLVMLibDriver.patch	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,18 @@
+# 24314638 LLVM CommandLine subsystem is busted
+# 3.9.X upstream.
+--- lib/LibDriver/LibDriver.cpp	2015-10-21 09:30:42.000000000 -0700
++++ lib/LibDriver/LibDriver.cpp	2016-05-12 19:17:43.286044625 -0700
+@@ -100,10 +100,11 @@
+ }
+ 
+ int llvm::libDriverMain(llvm::ArrayRef<const char*> ArgsArr) {
+-  SmallVector<const char *, 20> NewArgs(ArgsArr.begin(), ArgsArr.end());
++  std::vector<const char*> NewArgs(ArgsArr.begin(), ArgsArr.end());
+   BumpPtrAllocator Alloc;
+   StringSaver Saver(Alloc);
+-  cl::ExpandResponseFiles(Saver, cl::TokenizeWindowsCommandLine, NewArgs);
++  llvm::cl::ExpandResponseFiles(Saver, cl::TokenizeWindowsCommandLine,
++                                NewArgs);
+   ArgsArr = NewArgs;
+ 
+   LibOptTable Table;
--- a/components/llvm/patches/008-DeclTemplate.patch	Thu Jul 28 16:15:45 2016 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,26 +0,0 @@
-# 1. Write copy-constructor and assignment operator.
-# https://llvm.org/bugs/show_bug.cgi?id=24608
---- tools/clang/include/clang/AST/DeclTemplate.h	2015-07-17 16:43:46.485713092 -0700
-+++ tools/clang/include/clang/AST/DeclTemplate.h	2015-07-17 17:55:26.681560803 -0700
-@@ -485,6 +485,21 @@
-                                  const UnresolvedSetImpl &Templates,
-                                  const TemplateArgumentListInfo &TemplateArgs);
- 
-+  DependentFunctionTemplateSpecializationInfo(
-+            const DependentFunctionTemplateSpecializationInfo &RHS) 
-+  : NumTemplates(RHS.NumTemplates), NumArgs(RHS.NumArgs),
-+  AngleLocs(RHS.AngleLocs) { }
-+
-+  DependentFunctionTemplateSpecializationInfo
-+  &operator=(const DependentFunctionTemplateSpecializationInfo &RHS) {
-+    if (this != &RHS) {
-+      NumTemplates = RHS.NumTemplates;
-+      NumArgs = RHS.NumArgs;
-+      AngleLocs = RHS.AngleLocs;
-+    }
-+    return *this;
-+  }
-+
-   /// \brief Returns the number of function templates that this might
-   /// be a specialization of.
-   unsigned getNumTemplates() const { return NumTemplates; }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/008-solaris-clang-libclangAST.patch	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,1178 @@
+# Miscellaenous alignment assertions and fixes.
+# Remove bitfields if possible (not always possible).
+# Upstream loves bitfields.
+# 3.9.X upstream.
+--- tools/clang/include/clang/AST/DeclCXX.h	2015-12-29 22:24:14.000000000 -0500
++++ tools/clang/include/clang/AST/DeclCXX.h	2016-05-08 23:19:20.540430947 -0400
+@@ -2120,6 +2120,10 @@
+ 
+   friend TrailingObjects;
+ };
++static_assert(
++    llvm::AlignOf<CXXCtorInitializer>::Alignment >=
++        llvm::AlignOf<VarDecl *>::Alignment,
++    "Alignment is insufficient for objects appended to CXXCtorInitializer");
+ 
+ /// \brief Represents a C++ constructor within a class.
+ ///
+--- tools/clang/include/clang/AST/DeclFriend.h	2015-12-29 17:13:13.000000000 -0500
++++ tools/clang/include/clang/AST/DeclFriend.h	2016-05-08 23:19:20.540430947 -0400
+@@ -168,6 +168,9 @@
+   friend class ASTDeclWriter;
+   friend TrailingObjects;
+ };
++static_assert(llvm::AlignOf<FriendDecl>::Alignment >=
++                  llvm::AlignOf<TemplateParameterList *>::Alignment,
++              "Alignment is insufficient for objects appended to FriendDecl");
+ 
+ /// An iterator over the friend declarations of a class.
+ class CXXRecordDecl::friend_iterator {
+--- tools/clang/include/clang/AST/DeclGroup.h	2015-12-29 17:13:13.000000000 -0500
++++ tools/clang/include/clang/AST/DeclGroup.h	2016-05-08 23:19:20.541430972 -0400
+@@ -14,6 +14,7 @@
+ #ifndef LLVM_CLANG_AST_DECLGROUP_H
+ #define LLVM_CLANG_AST_DECLGROUP_H
+ 
++#include "llvm/Support/AlignOf.h"
+ #include "llvm/Support/DataTypes.h"
+ #include "llvm/Support/TrailingObjects.h"
+ #include <cassert>
+@@ -50,6 +51,9 @@
+ 
+   friend TrailingObjects;
+ };
++static_assert(llvm::AlignOf<DeclGroup>::Alignment >=
++                  llvm::AlignOf<Decl *>::Alignment,
++              "Alignment is insufficient for objects appended to DeclGroup");
+ 
+ class DeclGroupRef {
+   // Note this is not a PointerIntPair because we need the address of the
+--- tools/clang/include/clang/AST/Decl.h	2016-01-06 17:49:11.000000000 -0500
++++ tools/clang/include/clang/AST/Decl.h	2016-05-08 23:19:20.542430996 -0400
+@@ -3713,6 +3713,9 @@
+   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
+   static bool classofKind(Kind K) { return K == Import; }
+ };
++static_assert(llvm::AlignOf<ImportDecl>::Alignment >=
++                  llvm::AlignOf<SourceLocation>::Alignment,
++              "Alignment is insufficient for objects appended to ImportDecl");
+ 
+ /// \brief Represents an empty-declaration.
+ class EmptyDecl : public Decl {
+--- tools/clang/include/clang/AST/DeclOpenMP.h	2015-12-29 17:13:13.000000000 -0500
++++ tools/clang/include/clang/AST/DeclOpenMP.h	2016-05-08 23:19:20.542430996 -0400
+@@ -85,6 +85,10 @@
+   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
+   static bool classofKind(Kind K) { return K == OMPThreadPrivate; }
+ };
++static_assert(
++    llvm::AlignOf<OMPThreadPrivateDecl>::Alignment >=
++        llvm::AlignOf<Expr *>::Alignment,
++    "Alignment is insufficient for objects appended to OMPThreadPrivateDecl");
+ 
+ }  // end namespace clang
+ 
+###
+--- tools/clang/include/clang/AST/DeclTemplate.h	2015-12-29 14:13:13.000000000 -0800
++++ tools/clang/include/clang/AST/DeclTemplate.h	2016-05-09 13:56:11.451547165 -0700
+@@ -56,11 +56,11 @@
+ 
+   /// The number of template parameters in this template
+   /// parameter list.
+-  unsigned NumParams : 31;
++  unsigned NumParams;
+ 
+   /// Whether this template parameter list contains an unexpanded parameter
+   /// pack.
+-  unsigned ContainsUnexpandedParameterPack : 1;
++  bool ContainsUnexpandedParameterPack;
+ 
+ protected:
+   size_t numTrailingObjects(OverloadToken<NamedDecl *>) const {
+@@ -138,6 +138,10 @@
+   friend TrailingObjects;
+   template <size_t N> friend class FixedSizeTemplateParameterListStorage;
+ };
++static_assert(
++    llvm::AlignOf<TemplateParameterList>::Alignment >=
++        llvm::AlignOf<NamedDecl *>::Alignment,
++    "Insufficient alignment for objects appended to TemplateParameterList");
+ 
+ /// \brief Stores a list of template parameters for a TemplateDecl and its
+ /// derived classes. Suitable for creating on the stack.
+@@ -582,6 +586,21 @@
+   Create(ASTContext &Context, const UnresolvedSetImpl &Templates,
+          const TemplateArgumentListInfo &TemplateArgs);
+ 
++  DependentFunctionTemplateSpecializationInfo(
++    const DependentFunctionTemplateSpecializationInfo &RHS)
++    : NumTemplates(RHS.NumTemplates), NumArgs(RHS.NumArgs),
++    AngleLocs(RHS.AngleLocs) { }
++
++  DependentFunctionTemplateSpecializationInfo
++    &operator=(const DependentFunctionTemplateSpecializationInfo &RHS) {
++      if (this != &RHS) {
++        NumTemplates = RHS.NumTemplates;
++        NumArgs = RHS.NumArgs;
++        AngleLocs = RHS.AngleLocs;
++      }
++      return *this;
++    }
++
+   /// \brief Returns the number of function templates that this might
+   /// be a specialization of.
+   unsigned getNumTemplates() const { return NumTemplates; }
+@@ -617,6 +636,16 @@
+   friend TrailingObjects;
+ };
+ 
++static_assert(
++  llvm::AlignOf<DependentFunctionTemplateSpecializationInfo>::Alignment >=
++  llvm::AlignOf<TemplateArgumentLoc>::Alignment,
++  "Insufficient alignment for objects appended to "
++  "DependentFunctionTemplateSpecializationInfo");
++static_assert(llvm::AlignOf<TemplateArgumentLoc>::Alignment >=
++              llvm::AlignOf<FunctionTemplateDecl *>::Alignment,
++              "Insufficient alignment for objects appended to "
++              "DependentFunctionTemplateSpecializationInfo");
++
+ /// Declaration of a redeclarable template.
+ class RedeclarableTemplateDecl : public TemplateDecl, 
+                                  public Redeclarable<RedeclarableTemplateDecl> 
+@@ -1310,6 +1339,10 @@
+   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
+   static bool classofKind(Kind K) { return K == NonTypeTemplateParm; }
+ };
++static_assert(llvm::AlignOf<NonTypeTemplateParmDecl>::Alignment >=
++                  llvm::AlignOf<void *>::Alignment,
++              "Insufficient alignment for objects appended to "
++              "NonTypeTemplateParmDecl");
+ 
+ /// TemplateTemplateParmDecl - Declares a template template parameter,
+ /// e.g., "T" in
+@@ -1478,6 +1511,10 @@
+   friend class ASTDeclWriter;
+   friend TrailingObjects;
+ };
++static_assert(llvm::AlignOf<TemplateTemplateParmDecl>::Alignment >=
++                  llvm::AlignOf<TemplateParameterList *>::Alignment,
++              "Insufficient alignment for objects appended to "
++              "TemplateTemplateParmDecl");
+ 
+ /// \brief Represents the builtin template declaration which is used to
+ /// implement __make_integer_seq.  It serves no real purpose beyond existing as
+###
+--- tools/clang/include/clang/AST/ExprCXX.h	2016-01-06 14:34:54.000000000 -0800
++++ tools/clang/include/clang/AST/ExprCXX.h	2016-05-09 14:06:13.555769345 -0700
+@@ -1013,6 +1013,11 @@
+   friend class ASTStmtWriter;
+ };
+ 
++static_assert(llvm::AlignOf<CXXDefaultArgExpr>::Alignment >=
++              llvm::AlignOf<Expr *>::Alignment,
++              "Insufficient alignment for objects appended to "
++              "CXXDefaultArgExpr");
++
+ /// \brief A use of a default initializer in a constructor or in aggregate
+ /// initialization.
+ ///
+@@ -1678,6 +1683,17 @@
+   friend class ASTStmtWriter;
+ };
+ 
++static_assert(llvm::AlignOf<LambdaExpr>::Alignment >=
++              llvm::AlignOf<Stmt *>::Alignment,
++              "Insufficient alignment for objects appended to LambdaExpr");
++static_assert(llvm::AlignOf<Stmt *>::Alignment >=
++                  llvm::AlignOf<unsigned>::Alignment,
++              "Insufficient alignment for objects appended to LambdaExpr");
++// Code re-aligns before VarDecl *[]
++static_assert(llvm::AlignOf<LambdaExpr>::Alignment >=
++                  llvm::AlignOf<VarDecl *>::Alignment,
++              "Insufficient alignment for objects appended to LambdaExpr");
++
+ /// An expression "T()" which creates a value-initialized rvalue of type
+ /// T, which is a non-class type.  See (C++98 [5.2.3p2]).
+ class CXXScalarValueInitExpr : public Expr {
+@@ -2264,6 +2280,11 @@
+   friend class ASTStmtWriter;
+ };
+ 
++static_assert(
++    llvm::AlignOf<TypeTraitExpr>::Alignment >=
++    llvm::AlignOf<TypeSourceInfo *>::Alignment,
++    "Insufficient alignment for objects appended to TypeTraitExpr");
++
+ /// \brief An Embarcadero array type trait, as used in the implementation of
+ /// __array_rank and __array_extent.
+ ///
+@@ -2399,7 +2420,7 @@
+ 
+ /// \brief A reference to an overloaded function set, either an
+ /// \c UnresolvedLookupExpr or an \c UnresolvedMemberExpr.
+-class OverloadExpr : public Expr {
++class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) OverloadExpr : public Expr {
+   /// \brief The common name of these declarations.
+   DeclarationNameInfo NameInfo;
+ 
+@@ -2689,6 +2710,11 @@
+   }
+ };
+ 
++static_assert(llvm::AlignOf<UnresolvedLookupExpr>::Alignment >=
++              llvm::AlignOf<ASTTemplateKWAndArgsInfo>::Alignment,
++              "Insufficient alignment for objects appended to "
++              "UnresolvedLookupExpr");
++
+ /// \brief A qualified reference to a name whose declaration cannot
+ /// yet be resolved.
+ ///
+@@ -2834,6 +2860,11 @@
+   friend class ASTStmtWriter;
+ };
+ 
++static_assert(llvm::AlignOf<DependentScopeDeclRefExpr>::Alignment >=
++              llvm::AlignOf<ASTTemplateKWAndArgsInfo>::Alignment,
++              "Insufficient alignment for objects appended to "
++              "DependentScopeDeclRefExpr");
++
+ /// Represents an expression -- generally a full-expression -- that
+ /// introduces cleanups to be run at the end of the sub-expression's
+ /// evaluation.  The most common source of expression-introduced
+@@ -2903,6 +2934,11 @@
+   child_range children() { return child_range(&SubExpr, &SubExpr + 1); }
+ };
+ 
++static_assert(llvm::AlignOf<ExprWithCleanups>::Alignment >=
++              llvm::AlignOf<ExprWithCleanups::CleanupObject>::Alignment,
++              "Insufficient alignment for objects appended to "
++              "ExprWithCleanups");
++
+ /// \brief Describes an explicit type conversion that uses functional
+ /// notion but could not be resolved because one or more arguments are
+ /// type-dependent.
+@@ -3024,6 +3060,11 @@
+   }
+ };
+ 
++static_assert(llvm::AlignOf<CXXUnresolvedConstructExpr>::Alignment >=
++              llvm::AlignOf<Expr *>::Alignment,
++              "Insufficient alignment for objects appended to "
++              "CXXUnresolvedConstructExpr");
++
+ /// \brief Represents a C++ member access expression where the actual
+ /// member referenced could not be resolved because the base
+ /// expression or the member name was dependent.
+@@ -3046,11 +3087,11 @@
+ 
+   /// \brief Whether this member expression used the '->' operator or
+   /// the '.' operator.
+-  bool IsArrow : 1;
++  bool IsArrow;
+ 
+   /// \brief Whether this member expression has info for explicit template
+   /// keyword and arguments.
+-  bool HasTemplateKWAndArgsInfo : 1;
++  bool HasTemplateKWAndArgsInfo;
+ 
+   /// \brief The location of the '->' or '.' operator.
+   SourceLocation OperatorLoc;
+@@ -3250,6 +3291,11 @@
+   friend class ASTStmtWriter;
+ };
+ 
++static_assert(llvm::AlignOf<CXXDependentScopeMemberExpr>::Alignment >=
++              llvm::AlignOf<ASTTemplateKWAndArgsInfo>::Alignment,
++              "Insufficient alignment for objects appended to "
++              "CXXDependentScopeMemberExpr");
++
+ /// \brief Represents a C++ member access expression for which lookup
+ /// produced a set of overloaded functions.
+ ///
+@@ -3271,11 +3317,11 @@
+           UnresolvedMemberExpr, ASTTemplateKWAndArgsInfo, TemplateArgumentLoc> {
+   /// \brief Whether this member expression used the '->' operator or
+   /// the '.' operator.
+-  bool IsArrow : 1;
++  bool IsArrow;
+ 
+   /// \brief Whether the lookup results contain an unresolved using
+   /// declaration.
+-  bool HasUnresolvedUsing : 1;
++  bool HasUnresolvedUsing;
+ 
+   /// \brief The expression for the base pointer or class reference,
+   /// e.g., the \c x in x.f.
+@@ -3399,6 +3445,11 @@
+   }
+ };
+ 
++static_assert(llvm::AlignOf<UnresolvedMemberExpr>::Alignment >=
++              llvm::AlignOf<ASTTemplateKWAndArgsInfo>::Alignment,
++              "Insufficient alignment for objects appended to "
++              "UnresolvedMemberExpr");
++
+ inline ASTTemplateKWAndArgsInfo *
+ OverloadExpr::getTrailingASTTemplateKWAndArgsInfo() {
+   if (!HasTemplateKWAndArgsInfo)
+@@ -3841,6 +3892,11 @@
+   }
+ };
+ 
++static_assert(llvm::AlignOf<FunctionParmPackExpr>::Alignment >=
++              llvm::AlignOf<ParmVarDecl *>::Alignment,
++              "Insufficient alignment for objects appended to "
++              "FunctionParmPackExpr");
++
+ /// \brief Represents a prvalue temporary that is written into memory so that
+ /// a reference can bind to it.
+ ///
+###
+--- tools/clang/include/clang/AST/Expr.h	2016-01-07 12:59:26.000000000 -0800
++++ tools/clang/include/clang/AST/Expr.h	2016-05-09 13:48:08.744463290 -0700
+@@ -1142,6 +1142,17 @@
+   friend class ASTStmtWriter;
+ };
+ 
++static_assert(llvm::AlignOf<DeclRefExpr>::Alignment >=
++                  llvm::AlignOf<NestedNameSpecifierLoc>::Alignment,
++              "Alignment is insufficient for objects appended to DeclRefExpr");
++static_assert(llvm::AlignOf<NestedNameSpecifierLoc>::Alignment >=
++                  llvm::AlignOf<NamedDecl *>::Alignment,
++              "Alignment is insufficient for objects appended to NestedNameSpecifierLoc");
++// Code re-aligns before ASTTemplateKWAndArgsInfo
++static_assert(llvm::AlignOf<DeclRefExpr>::Alignment >=
++                  llvm::AlignOf<ASTTemplateKWAndArgsInfo>::Alignment,
++              "Alignment is insufficient for objects appended to DeclRefExpr");
++
+ /// \brief [C99 6.4.2.2] - A predefined identifier such as __func__.
+ class PredefinedExpr : public Expr {
+ public:
+@@ -1753,7 +1764,7 @@
+ /// Helper class for OffsetOfExpr.
+ 
+ // __builtin_offsetof(type, identifier(.identifier|[expr])*)
+-class OffsetOfNode {
++class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) OffsetOfNode {
+ public:
+   /// \brief The kind of offsetof node we have.
+   enum Kind {
+@@ -1857,7 +1868,7 @@
+ /// @endcode
+ /// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
+ 
+-class OffsetOfExpr final
++class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) OffsetOfExpr final
+     : public Expr,
+       private llvm::TrailingObjects<OffsetOfExpr, OffsetOfNode, Expr *> {
+   SourceLocation OperatorLoc, RParenLoc;
+@@ -1954,6 +1965,22 @@
+   friend TrailingObjects;
+ };
+ 
++static_assert(llvm::AlignOf<OffsetOfExpr>::Alignment >=
++                  llvm::AlignOf<OffsetOfNode*>::Alignment,
++              "Insufficient aligment for objects appended to OffsetOfExpr");
++static_assert(llvm::AlignOf<OffsetOfNode>::Alignment >=
++                  llvm::AlignOf<Expr*>::Alignment,
++              "Insufficient alignment for objects appended to OffsetOfExpr");
++
++#if 0
++static_assert(llvm::AlignOf<OffsetOfExpr>::Alignment >=
++                  llvm::AlignOf<OffsetOfExpr::OffsetOfNode *>::Alignment,
++              "Alignment is insufficient for objects appended to OffsetOfExpr");
++static_assert(llvm::AlignOf<OffsetOfExpr::OffsetOfNode>::Alignment >=
++                  llvm::AlignOf<Expr *>::Alignment,
++              "Alignment is insufficient for objects appended to OffsetOfExpr");
++#endif
++
+ /// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated)
+ /// expression operand.  Used for sizeof/alignof (C99 6.5.3.4) and
+ /// vec_step (OpenCL 1.1 6.11.12).
+@@ -2318,24 +2345,24 @@
+   SourceLocation OperatorLoc;
+ 
+   /// IsArrow - True if this is "X->F", false if this is "X.F".
+-  bool IsArrow : 1;
++  bool IsArrow;
+ 
+   /// \brief True if this member expression used a nested-name-specifier to
+   /// refer to the member, e.g., "x->Base::f", or found its member via a using
+   /// declaration.  When true, a MemberExprNameQualifier
+   /// structure is allocated immediately after the MemberExpr.
+-  bool HasQualifierOrFoundDecl : 1;
++  bool HasQualifierOrFoundDecl;
+ 
+   /// \brief True if this member expression specified a template keyword
+   /// and/or a template argument list explicitly, e.g., x->f<int>,
+   /// x->template f, x->template f<int>.
+   /// When true, an ASTTemplateKWAndArgsInfo structure and its
+   /// TemplateArguments (if any) are present.
+-  bool HasTemplateKWAndArgsInfo : 1;
++  bool HasTemplateKWAndArgsInfo;
+ 
+   /// \brief True if this member expression refers to a method that
+   /// was resolved from an overloaded set having size greater than 1.
+-  bool HadMultipleCandidates : 1;
++  bool HadMultipleCandidates;
+ 
+   size_t numTrailingObjects(OverloadToken<MemberExprNameQualifier>) const {
+     return HasQualifierOrFoundDecl ? 1 : 0;
+@@ -2688,6 +2715,11 @@
+   // Iterators
+   child_range children() { return child_range(&Op, &Op+1); }
+ };
++static_assert(llvm::AlignOf<CastExpr>::Alignment >=
++                  llvm::AlignOf<CXXBaseSpecifier *>::Alignment,
++              "Alignment is insufficient for objects appended to CastExpr");
++// (Note that the data is actually tacked onto one of its subclasses,
++// but they'll inherit alignment)
+ 
+ /// ImplicitCastExpr - Allows us to explicitly represent implicit type
+ /// conversions, which have no direct representation in the original
+@@ -4316,6 +4348,10 @@
+     return child_range(&BaseAndUpdaterExprs[0], &BaseAndUpdaterExprs[0] + 2);
+   }
+ };
++static_assert(
++    llvm::AlignOf<DesignatedInitExpr>::Alignment >=
++        llvm::AlignOf<Stmt *>::Alignment,
++    "Alignment is insufficient for objects appended to DesignatedInitExpr");
+ 
+ /// \brief Represents an implicitly-generated value initialization of
+ /// an object of a given type.
+@@ -4808,6 +4844,10 @@
+   friend TrailingObjects;
+   friend class ASTStmtReader;
+ };
++static_assert(
++    llvm::AlignOf<PseudoObjectExpr>::Alignment >=
++        llvm::AlignOf<Expr *>::Alignment,
++    "Alignment is insufficient for objects appended to PseudoObjectExpr");
+ 
+ /// AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*,
+ /// __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the
+###
+--- tools/clang/include/clang/AST/ExprObjC.h	2015-12-30 20:43:19.000000000 -0800
++++ tools/clang/include/clang/AST/ExprObjC.h	2016-05-09 14:56:41.962219122 -0700
+@@ -206,6 +206,10 @@
+   friend TrailingObjects;
+   friend class ASTStmtReader;
+ };
++static_assert(
++    llvm::AlignOf<ObjCArrayLiteral>::Alignment >=
++        llvm::AlignOf<Expr *>::Alignment,
++    "Alignment is insufficient for objects appended to ObjCArrayLiteral");
+ 
+ /// \brief An element in an Objective-C dictionary literal.
+ ///
+@@ -260,7 +264,7 @@
+                                     ObjCDictionaryLiteral_KeyValuePair,
+                                     ObjCDictionaryLiteral_ExpansionData> {
+   /// \brief The number of elements in this dictionary literal.
+-  unsigned NumElements : 31;
++  unsigned NumElements;
+ 
+   /// \brief Determine whether this dictionary literal has any pack expansions.
+   ///
+@@ -269,11 +273,12 @@
+   /// key/value pairs, which provide the locations of the ellipses (if
+   /// any) and number of elements in the expansion (if known). If
+   /// there are no pack expansions, we optimize away this storage.
+-  unsigned HasPackExpansions : 1;
++  bool HasPackExpansions;
+ 
+   SourceRange Range;
+   ObjCMethodDecl *DictWithObjectsMethod;
+ 
++public:
+   typedef ObjCDictionaryLiteral_KeyValuePair KeyValuePair;
+   typedef ObjCDictionaryLiteral_ExpansionData ExpansionData;
+ 
+@@ -347,7 +352,14 @@
+   friend class ASTStmtWriter;
+   friend TrailingObjects;
+ };
+-
++static_assert(
++    llvm::AlignOf<ObjCDictionaryLiteral>::Alignment >=
++        llvm::AlignOf<ObjCDictionaryLiteral::KeyValuePair>::Alignment,
++    "Alignment is insufficient for objects appended to ObjCDictionaryLiteral");
++static_assert(
++    llvm::AlignOf<ObjCDictionaryLiteral::KeyValuePair>::Alignment >=
++        llvm::AlignOf<ObjCDictionaryLiteral::ExpansionData>::Alignment,
++    "Alignment is insufficient for objects appended to ObjCDictionaryLiteral");
+ 
+ /// ObjCEncodeExpr, used for \@encode in Objective-C.  \@encode has the same
+ /// type and behavior as StringLiteral except that the string initializer is
+@@ -1377,6 +1389,17 @@
+   friend class ASTStmtReader;
+   friend class ASTStmtWriter;
+ };
++static_assert(
++    llvm::AlignOf<ObjCMessageExpr>::Alignment >=
++        llvm::AlignOf<void *>::Alignment,
++    "Alignment is insufficient for objects appended to ObjCMessageExpr");
++static_assert(
++    llvm::AlignOf<void *>::Alignment >= llvm::AlignOf<Expr *>::Alignment,
++    "Alignment is insufficient for objects appended to ObjCMessageExpr");
++static_assert(
++    llvm::AlignOf<Expr *>::Alignment >=
++        llvm::AlignOf<SourceLocation>::Alignment,
++    "Alignment is insufficient for objects appended to ObjCMessageExpr");
+ 
+ /// ObjCIsaExpr - Represent X->isa and X.isa when X is an ObjC 'id' type.
+ /// (similar in spirit to MemberExpr).
+### NO PACE
+--- tools/clang/include/clang/AST/Mangle.h	2015-12-31 00:36:54.000000000 -0500
++++ tools/clang/include/clang/AST/Mangle.h	2016-05-08 23:19:20.547431117 -0400
+@@ -129,6 +129,8 @@
+ 
+   virtual void mangleDynamicInitializer(const VarDecl *D, raw_ostream &) = 0;
+ 
++  virtual void mangleGCCDynamicInitializer(const VarDecl *D, raw_ostream &) = 0;
++
+   virtual void mangleDynamicAtExitDestructor(const VarDecl *D,
+                                              raw_ostream &) = 0;
+ 
+--- tools/clang/include/clang/AST/StmtCXX.h	2015-11-23 21:34:39.000000000 -0500
++++ tools/clang/include/clang/AST/StmtCXX.h	2016-05-08 23:19:20.547431117 -0400
+@@ -118,6 +118,9 @@
+ 
+   friend class ASTStmtReader;
+ };
++static_assert(llvm::AlignOf<CXXTryStmt>::Alignment >=
++                  llvm::AlignOf<Stmt *>::Alignment,
++              "Alignment is insufficient for objects appended to CXXTryStmt");
+ 
+ /// CXXForRangeStmt - This represents C++0x [stmt.ranged]'s ranged for
+ /// statement, represented as 'for (range-declarator : range-expression)'.
+--- tools/clang/include/clang/AST/Stmt.h	2016-01-07 15:59:26.000000000 -0500
++++ tools/clang/include/clang/AST/Stmt.h	2016-05-08 23:19:20.548431142 -0400
+@@ -862,7 +862,10 @@
+     return T->getStmtClass() == AttributedStmtClass;
+   }
+ };
+-
++static_assert(
++    llvm::AlignOf<AttributedStmt>::Alignment >=
++        llvm::AlignOf<Attr *>::Alignment,
++    "Alignment is insufficient for objects appended to AttributedStmt");
+ 
+ /// IfStmt - This represents an if/then/else.
+ ///
+@@ -2190,6 +2193,13 @@
+ 
+   friend class ASTStmtReader;
+ };
++static_assert(llvm::AlignOf<CapturedStmt>::Alignment >=
++                  llvm::AlignOf<Stmt *>::Alignment,
++              "Alignment is insufficient for objects appended to CapturedStmt");
++// Code re-aligns before Capture[]
++static_assert(llvm::AlignOf<CapturedStmt>::Alignment >=
++                  llvm::AlignOf<CapturedStmt::Capture>::Alignment,
++              "Alignment is insufficient for objects appended to CapturedStmt");
+ 
+ }  // end namespace clang
+ 
+--- tools/clang/include/clang/AST/StmtObjC.h	2015-04-02 11:29:07.000000000 -0400
++++ tools/clang/include/clang/AST/StmtObjC.h	2016-05-08 23:19:20.549431166 -0400
+@@ -250,6 +250,9 @@
+                        getStmts() + 1 + NumCatchStmts + HasFinally);
+   }
+ };
++static_assert(
++    llvm::AlignOf<ObjCAtTryStmt>::Alignment >= llvm::AlignOf<Stmt *>::Alignment,
++    "Alignment is insufficient for objects appended to ObjCAtTryStmt");
+ 
+ /// \brief Represents Objective-C's \@synchronized statement.
+ ///
+###
+--- tools/clang/include/clang/AST/TemplateBase.h	2015-12-29 10:15:14.000000000 -0800
++++ tools/clang/include/clang/AST/TemplateBase.h	2016-05-09 13:37:13.627921073 -0700
+@@ -85,8 +85,8 @@
+     // We store a decomposed APSInt with the data allocated by ASTContext if
+     // BitWidth > 64. The memory may be shared between multiple
+     // TemplateArgument instances.
+-    unsigned BitWidth : 31;
+-    unsigned IsUnsigned : 1;
++    unsigned BitWidth;
++    bool IsUnsigned;
+     union {
+       uint64_t VAL;          ///< Used to store the <= 64 bits integer value.
+       const uint64_t *pVal;  ///< Used to store the >64 bits integer value.
+@@ -113,19 +113,36 @@
+     struct A Args;
+     struct TA TemplateArg;
+     struct TV TypeOrValue;
++    uint64_t Buffer[8];
+   };
+ 
+   TemplateArgument(TemplateName, bool) = delete;
+-  
++
+ public:
+   /// \brief Construct an empty, invalid template argument.
+   TemplateArgument() {
++    (void) std::memset(Buffer, 0, sizeof(Buffer));
+     TypeOrValue.Kind = Null;
+     TypeOrValue.V = 0;
+   }
+ 
++
++  TemplateArgument(const TemplateArgument &RHS) {
++    (void) std::memset(Buffer, 0, sizeof(Buffer));
++    (void) std::memcpy(Buffer, RHS.Buffer, sizeof(Buffer));
++  }
++
++  TemplateArgument &operator=(const TemplateArgument &RHS) {
++    if (this != &RHS) {
++      (void) std::memset(Buffer, 0, sizeof(Buffer));
++      (void) std::memcpy(Buffer, RHS.Buffer, sizeof(Buffer));
++    }
++    return *this;
++  }
++
+   /// \brief Construct a template type argument.
+   TemplateArgument(QualType T, bool isNullPtr = false) {
++    (void) std::memset(Buffer, 0, sizeof(Buffer));
+     TypeOrValue.Kind = isNullPtr ? NullPtr : Type;
+     TypeOrValue.V = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
+   }
+@@ -135,6 +152,7 @@
+   /// template declaration.
+   TemplateArgument(ValueDecl *D, QualType QT) {
+     assert(D && "Expected decl");
++    (void) std::memset(Buffer, 0, sizeof(Buffer));
+     DeclArg.Kind = Declaration;
+     DeclArg.QT = QT.getAsOpaquePtr();
+     DeclArg.D = D;
+@@ -147,6 +165,7 @@
+   /// \brief Construct an integral constant template argument with the same
+   /// value as Other but a different type.
+   TemplateArgument(const TemplateArgument &Other, QualType Type) {
++    (void) std::memset(Buffer, 0, sizeof(Buffer));
+     Integer = Other.Integer;
+     Integer.Type = Type.getAsOpaquePtr();
+   }
+@@ -160,6 +179,7 @@
+   ///
+   /// \param Name The template name.
+   TemplateArgument(TemplateName Name) {
++    (void) std::memset(Buffer, 0, sizeof(Buffer));
+     TemplateArg.Kind = Template;
+     TemplateArg.Name = Name.getAsVoidPointer();
+     TemplateArg.NumExpansions = 0;
+@@ -177,6 +197,7 @@
+   /// \param NumExpansions The number of expansions that will be generated by
+   /// instantiating
+   TemplateArgument(TemplateName Name, Optional<unsigned> NumExpansions) {
++    (void) std::memset(Buffer, 0, sizeof(Buffer));
+     TemplateArg.Kind = TemplateExpansion;
+     TemplateArg.Name = Name.getAsVoidPointer();
+     if (NumExpansions)
+@@ -191,6 +212,7 @@
+   /// lists used for dependent types and for expression; it will not
+   /// occur in a non-dependent, canonical template argument list.
+   TemplateArgument(Expr *E) {
++    (void) std::memset(Buffer, 0, sizeof(Buffer));
+     TypeOrValue.Kind = Expression;
+     TypeOrValue.V = reinterpret_cast<uintptr_t>(E);
+   }
+@@ -200,6 +222,7 @@
+   /// We assume that storage for the template arguments provided
+   /// outlives the TemplateArgument itself.
+   explicit TemplateArgument(ArrayRef<TemplateArgument> Args) {
++    (void) std::memset(Buffer, 0, sizeof(Buffer));
+     this->Args.Kind = Pack;
+     this->Args.Args = Args.data();
+     this->Args.NumArgs = Args.size();
+@@ -358,6 +381,20 @@
+   void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) const;
+ };
+ 
++static_assert(llvm::AlignOf<TemplateSpecializationType>::Alignment >=
++                  llvm::AlignOf<TemplateArgument>::Alignment,
++              "Alignment is insufficient for objects appended to "
++              "TemplateSpecializationType");
++static_assert(llvm::AlignOf<TemplateArgument>::Alignment >=
++                  llvm::AlignOf<QualType>::Alignment,
++              "Alignment is insufficient for objects appended to "
++              "TemplateSpecializationType");
++
++static_assert(llvm::AlignOf<DependentTemplateSpecializationType>::Alignment >=
++                  llvm::AlignOf<TemplateArgument>::Alignment,
++              "Alignment is insufficient for objects appended to "
++              "DependentTemplateSpecializationType");
++
+ /// Location information for a TemplateArgument.
+ struct TemplateArgumentLocInfo {
+ private:
+@@ -375,25 +412,55 @@
+     struct T Template;
+     Expr *Expression;
+     TypeSourceInfo *Declarator;
++    unsigned long Buffer[4];
+   };
+ 
+ public:
+   TemplateArgumentLocInfo();
+-  
+-  TemplateArgumentLocInfo(TypeSourceInfo *TInfo) : Declarator(TInfo) {}
+-  
+-  TemplateArgumentLocInfo(Expr *E) : Expression(E) {}
+-  
++
++  TemplateArgumentLocInfo(TypeSourceInfo *TInfo) {
++    (void) std::memset(Buffer, 0, sizeof(Buffer));
++    Declarator = TInfo;
++  }
++
++  TemplateArgumentLocInfo(Expr *E) {
++    (void) std::memset(Buffer, 0, sizeof(Buffer));
++    Expression = E;
++  }
++
+   TemplateArgumentLocInfo(NestedNameSpecifierLoc QualifierLoc,
+                           SourceLocation TemplateNameLoc,
+-                          SourceLocation EllipsisLoc)
+-  {
++                          SourceLocation EllipsisLoc) {
++    (void) std::memset(Buffer, 0, sizeof(Buffer));
+     Template.Qualifier = QualifierLoc.getNestedNameSpecifier();
+     Template.QualifierLocData = QualifierLoc.getOpaqueData();
+     Template.TemplateNameLoc = TemplateNameLoc.getRawEncoding();
+     Template.EllipsisLoc = EllipsisLoc.getRawEncoding();
+   }
+ 
++  TemplateArgumentLocInfo(const TemplateArgumentLocInfo &RHS) {
++    (void) std::memset(Buffer, 0, sizeof(Buffer));
++    Template.Qualifier = RHS.Template.Qualifier;
++    Template.QualifierLocData = RHS.Template.QualifierLocData;
++    Template.TemplateNameLoc = RHS.Template.TemplateNameLoc;
++    Template.EllipsisLoc = RHS.Template.EllipsisLoc;
++    Expression = RHS.Expression;
++    Declarator = RHS.Declarator;
++  }
++
++    TemplateArgumentLocInfo &operator=(const TemplateArgumentLocInfo &RHS) {
++      if (this != &RHS) {
++        (void) std::memset(Buffer, 0, sizeof(Buffer));
++        Template.Qualifier = RHS.Template.Qualifier;
++        Template.QualifierLocData = RHS.Template.QualifierLocData;
++        Template.TemplateNameLoc = RHS.Template.TemplateNameLoc;
++        Template.EllipsisLoc = RHS.Template.EllipsisLoc;
++        Expression = RHS.Expression;
++        Declarator = RHS.Declarator;
++      }
++      return *this;
++    }
++
+   TypeSourceInfo *getAsTypeSourceInfo() const {
+     return Declarator;
+   }
+@@ -403,14 +470,14 @@
+   }
+ 
+   NestedNameSpecifierLoc getTemplateQualifierLoc() const {
+-    return NestedNameSpecifierLoc(Template.Qualifier, 
++    return NestedNameSpecifierLoc(Template.Qualifier,
+                                   Template.QualifierLocData);
+   }
+-  
++
+   SourceLocation getTemplateNameLoc() const {
+     return SourceLocation::getFromRawEncoding(Template.TemplateNameLoc);
+   }
+-  
++
+   SourceLocation getTemplateEllipsisLoc() const {
+     return SourceLocation::getFromRawEncoding(Template.EllipsisLoc);
+   }
+@@ -593,6 +660,10 @@
+   static const ASTTemplateArgumentListInfo *
+   Create(ASTContext &C, const TemplateArgumentListInfo &List);
+ };
++static_assert(llvm::AlignOf<ASTTemplateArgumentListInfo>::Alignment >=
++                  llvm::AlignOf<TemplateArgumentLoc>::Alignment,
++              "Alignment is insufficient for objects appended to "
++              "ASTTemplateArgumentListInfo");
+ 
+ /// \brief Represents an explicit template argument list in C++, e.g.,
+ /// the "<int>" in "sort<int>".
+@@ -601,7 +672,7 @@
+ /// as such, doesn't contain the array of TemplateArgumentLoc itself,
+ /// but expects the containing object to also provide storage for
+ /// that.
+-struct LLVM_ALIGNAS(LLVM_PTR_SIZE) ASTTemplateKWAndArgsInfo {
++struct LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) ASTTemplateKWAndArgsInfo {
+   /// \brief The source location of the left angle bracket ('<').
+   SourceLocation LAngleLoc;
+ 
+@@ -630,6 +701,18 @@
+   void copyInto(const TemplateArgumentLoc *ArgArray,
+                 TemplateArgumentListInfo &List) const;
+ };
++static_assert(llvm::AlignOf<ASTTemplateKWAndArgsInfo>::Alignment >=
++                  llvm::AlignOf<TemplateArgumentLoc>::Alignment,
++              "Alignment is insufficient for objects appended to "
++              "ASTTemplateKWAndArgsInfo");
++static_assert(llvm::AlignOf<ASTTemplateKWAndArgsInfo>::Alignment >=
++                  llvm::AlignOf<SourceLocation>::Alignment,
++              "Alignment is insufficient for objects appended to "
++              "ASTTemplateKWAndArgsInfo");
++static_assert(llvm::AlignOf<TemplateArgumentLoc>::Alignment >=
++                  llvm::AlignOf<SourceLocation>::Alignment,
++              "Alignment is insufficient for objects appended to "
++              "ASTTemplateKWAndArgsInfo");
+ 
+ const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
+                                     const TemplateArgument &Arg);
+###
+--- tools/clang/include/clang/AST/TemplateName.h	2015-12-30 01:21:02.000000000 -0500
++++ tools/clang/include/clang/AST/TemplateName.h	2016-05-08 23:19:20.550431191 -0400
+@@ -108,6 +108,10 @@
+   iterator begin() const { return getStorage(); }
+   iterator end() const { return getStorage() + size(); }
+ };
++static_assert(llvm::AlignOf<OverloadedTemplateStorage>::Alignment >=
++                  llvm::AlignOf<NamedDecl *>::Alignment,
++              "Alignment is insufficient for objects appended to "
++              "OverloadedTemplateStorage");
+ 
+ /// \brief A structure for storing an already-substituted template template
+ /// parameter pack.
+--- tools/clang/include/clang/AST/Type.h	2016-01-09 07:53:17.000000000 -0500
++++ tools/clang/include/clang/AST/Type.h	2016-05-08 23:19:20.551431215 -0400
+@@ -3324,6 +3324,30 @@
+                       const ExtProtoInfo &EPI, const ASTContext &Context);
+ };
+ 
++static_assert(
++  llvm::AlignOf<FunctionProtoType>::Alignment >=
++  llvm::AlignOf<QualType>::Alignment,
++  "Alignment is insufficient for objects appended to FunctionProtoType");
++// After QualType[], there can be one of 4 options: more QualType, Expr*, 2x
++// FunctionDecl*, FunctionDecl*
++static_assert(
++  llvm::AlignOf<QualType>::Alignment >= llvm::AlignOf<Expr *>::Alignment,
++  "Alignment is insufficient for objects appended to FunctionProtoType");
++static_assert(
++  llvm::AlignOf<QualType>::Alignment >=
++  llvm::AlignOf<FunctionDecl *>::Alignment,
++  "Alignment is insufficient for objects appended to FunctionProtoType");
++// And then, after any of those options, comes bool[]
++static_assert(
++  llvm::AlignOf<QualType>::Alignment >= llvm::AlignOf<bool>::Alignment,
++  "Alignment is insufficient for objects appended to FunctionProtoType");
++static_assert(
++  llvm::AlignOf<Expr *>::Alignment >= llvm::AlignOf<bool>::Alignment,
++  "Alignment is insufficient for objects appended to FunctionProtoType");
++static_assert(
++  llvm::AlignOf<FunctionDecl *>::Alignment >= llvm::AlignOf<bool>::Alignment,
++  "Alignment is insufficient for objects appended to FunctionProtoType");
++
+ /// \brief Represents the dependent type named by a dependently-scoped
+ /// typename using declaration, e.g.
+ ///   using typename Base<T>::foo;
+@@ -3985,7 +4009,7 @@
+ /// TemplateArguments, followed by a QualType representing the
+ /// non-canonical aliased type when the template is a type alias
+ /// template.
+-class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) TemplateSpecializationType
++class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) TemplateSpecializationType
+     : public Type,
+       public llvm::FoldingSetNode {
+   /// The name of the template being specialized.  This is
+@@ -3999,10 +4023,10 @@
+ 
+   /// The number of template arguments named in this class template
+   /// specialization.
+-  unsigned NumArgs : 31;
++  unsigned NumArgs;
+ 
+   /// Whether this template specialization type is a substituted type alias.
+-  bool TypeAlias : 1;
++  bool TypeAlias;
+ 
+   TemplateSpecializationType(TemplateName T,
+                              const TemplateArgument *Args,
+@@ -4108,6 +4132,14 @@
+   }
+ };
+ 
++// static_assert(llvm::AlignOf<TemplateSpecializationType>::Alignment >=
++// llvm::AlignOf<TemplateArgument>::Alignment, "Alignment is insufficient for
++// objects appended to TemplateSpecializationType");
++// static_assert(llvm::AlignOf<TemplateArgument>::Alignment >=
++// llvm::AlignOf<QualType>::Alignment, "Alignment is insufficient for objects
++// appended to TemplateSpecializationType");
++// ^ Moved after class TemplateArgument, as it is is forward declared here.
++
+ /// The injected class name of a C++ class template or class
+ /// template partial specialization.  Used to record that a type was
+ /// spelled with a bare identifier rather than as a template-id; the
+@@ -4446,6 +4478,11 @@
+   }
+ };
+ 
++// static_assert(llvm::AlignOf<DependentTemplateSpecializationType>::Alignment
++// >= llvm::AlignOf<TemplateArgument>::Alignment, "Alignment is insufficient for
++// objects appended to DependentTemplateSpecializationType");
++// ^ Moved after class TemplateArgument, as it is is forward declared here.
++
+ /// \brief Represents a pack expansion of types.
+ ///
+ /// Pack expansions are part of C++11 variadic templates. A pack
+@@ -4742,6 +4779,11 @@
+                       bool isKindOf);
+ };
+ 
++static_assert(
++  llvm::AlignOf<ObjCObjectTypeImpl>::Alignment >=
++  llvm::AlignOf<ObjCProtocolDecl *>::Alignment,
++  "Alignment is insufficient for objects appended to ObjCObjectTypeImpl");
++
+ inline QualType *ObjCObjectType::getTypeArgStorage() {
+   return reinterpret_cast<QualType *>(static_cast<ObjCObjectTypeImpl*>(this)+1);
+ }
+--- tools/clang/lib/AST/DeclBase.cpp	2016-01-06 17:49:11.000000000 -0500
++++ tools/clang/lib/AST/DeclBase.cpp	2016-05-08 23:19:20.556431336 -0400
+@@ -46,9 +46,9 @@
+ }
+ 
+ #define DECL(DERIVED, BASE)                                                    \
+-  static_assert(Decl::DeclObjAlignment >=                                      \
++  static_assert(llvm::AlignOf<uint64_t>::Alignment >=                          \
+                     llvm::AlignOf<DERIVED##Decl>::Alignment,                   \
+-                "Alignment sufficient after objects prepended to " #DERIVED);
++                "Alignment is insufficient for objects prepended to " #DERIVED);
+ #define ABSTRACT_DECL(DECL)
+ #include "clang/AST/DeclNodes.inc"
+ 
+@@ -56,12 +56,15 @@
+                          unsigned ID, std::size_t Extra) {
+   // Allocate an extra 8 bytes worth of storage, which ensures that the
+   // resulting pointer will still be 8-byte aligned.
+-  static_assert(sizeof(unsigned) * 2 >= DeclObjAlignment,
++  static_assert(sizeof(unsigned) * 2 >= llvm::AlignOf<uint64_t>::Alignment,
+                 "Decl won't be misaligned");
+-  void *Start = Context.Allocate(Size + Extra + 8);
+-  void *Result = (char*)Start + 8;
++  void *Start = Context.Allocate(Size + Extra + 8, 8U);
++  void *Result = reinterpret_cast<void*>(
++    reinterpret_cast<unsigned char*>(
++      reinterpret_cast<unsigned char*>(Start) + 8));
+ 
+-  unsigned *PrefixPtr = (unsigned *)Result - 2;
++  unsigned *PrefixPtr =
++    reinterpret_cast<unsigned*>(reinterpret_cast<unsigned*>(Result) - 2);
+ 
+   // Zero out the first 4 bytes; this is used to store the owning module ID.
+   PrefixPtr[0] = 0;
+--- tools/clang/lib/AST/Decl.cpp	2016-01-12 04:01:25.000000000 -0500
++++ tools/clang/lib/AST/Decl.cpp	2016-05-08 23:19:20.557431361 -0400
+@@ -3240,8 +3240,8 @@
+ 
+ DependentFunctionTemplateSpecializationInfo *
+ DependentFunctionTemplateSpecializationInfo::Create(
+-    ASTContext &Context, const UnresolvedSetImpl &Ts,
+-    const TemplateArgumentListInfo &TArgs) {
++  ASTContext &Context, const UnresolvedSetImpl &Ts,
++  const TemplateArgumentListInfo &TArgs) {
+   void *Buffer = Context.Allocate(
+       totalSizeToAlloc<TemplateArgumentLoc, FunctionTemplateDecl *>(
+           TArgs.size(), Ts.size()));
+diff: tools/clang/lib/AST/Expr.cpp: No such file or directory
+--- tools/clang/lib/AST/ExprCXX.cpp	2016-01-06 17:34:54.000000000 -0500
++++ tools/clang/lib/AST/ExprCXX.cpp	2016-05-08 23:19:20.558431385 -0400
+@@ -1083,7 +1083,7 @@
+     *const_cast<clang::Stmt **>(&getStoredStmts()[NumCaptures]) =
+         getCallOperator()->getBody();
+ 
+-  return static_cast<CompoundStmt *>(getStoredStmts()[NumCaptures]);
++  return reinterpret_cast<CompoundStmt *>(getStoredStmts()[NumCaptures]);
+ }
+ 
+ bool LambdaExpr::isMutable() const {
+--- tools/clang/lib/AST/ItaniumMangle.cpp	2016-01-09 07:53:17.000000000 -0500
++++ tools/clang/lib/AST/ItaniumMangle.cpp	2016-05-08 23:19:20.559431409 -0400
+@@ -162,6 +162,8 @@
+   void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
+   void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;
+   void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
++  void mangleGCCDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
++
+   void mangleDynamicAtExitDestructor(const VarDecl *D,
+                                      raw_ostream &Out) override;
+   void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
+@@ -4133,6 +4135,17 @@
+   Out << "__cxx_global_var_init";
+ }
+ 
++void ItaniumMangleContextImpl::mangleGCCDynamicInitializer(const VarDecl *MD,
++                                                           raw_ostream &Out) {
++  static unsigned SEQ = 0UL;
++
++  // Mangle GCC's __static_initialiation_and_destruction_<X>
++  // .init_array function.
++  Out << "_Z41" << "__static_initialization_and_destruction_"
++    << SEQ << "ii";
++  ++SEQ;
++}
++
+ void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
+                                                              raw_ostream &Out) {
+   // Prefix the mangling of D with __dtor_.
+--- tools/clang/lib/AST/MicrosoftMangle.cpp	2016-01-09 07:53:17.000000000 -0500
++++ tools/clang/lib/AST/MicrosoftMangle.cpp	2016-05-08 23:19:20.560431434 -0400
+@@ -152,6 +152,8 @@
+   void mangleThreadSafeStaticGuardVariable(const VarDecl *D, unsigned GuardNum,
+                                            raw_ostream &Out) override;
+   void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
++  void mangleGCCDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
++
+   void mangleDynamicAtExitDestructor(const VarDecl *D,
+                                      raw_ostream &Out) override;
+   void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
+@@ -2857,6 +2859,12 @@
+ }
+ 
+ void
++MicrosoftMangleContextImpl::mangleGCCDynamicInitializer(const VarDecl *D,
++                                                        raw_ostream &Out) {
++  this->mangleDynamicInitializer(D, Out);
++}
++
++void
+ MicrosoftMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
+                                                           raw_ostream &Out) {
+   // <destructor-name> ::= ?__F <name> YAXXZ
+--- tools/clang/lib/AST/NestedNameSpecifier.cpp	2015-12-27 09:34:22.000000000 -0500
++++ tools/clang/lib/AST/NestedNameSpecifier.cpp	2016-05-08 23:19:20.560431434 -0400
+@@ -445,22 +445,41 @@
+ 
+     if (BufferSize + (End - Start) > BufferCapacity) {
+       // Reallocate the buffer.
+-      unsigned NewCapacity = std::max(
+-          (unsigned)(BufferCapacity ? BufferCapacity * 2 : sizeof(void *) * 2),
+-          (unsigned)(BufferSize + (End - Start)));
+-      char *NewBuffer = static_cast<char *>(malloc(NewCapacity));
+-      if (BufferCapacity) {
+-        memcpy(NewBuffer, Buffer, BufferSize);
+-        free(Buffer);
+-      }
++      unsigned NewCapacity =
++        std::max((unsigned)(BufferCapacity ? BufferCapacity * 2
++            : sizeof(void*) * 2), (unsigned)(BufferSize + (End - Start)));
++
++      NewCapacity =
++        llvm::RoundUpToAlignment(NewCapacity, llvm::alignOf<uint64_t>());
++      unsigned Alignment = ((NewCapacity < 5) ? 4 : 8);
++      if (NewCapacity < Alignment)
++        NewCapacity = Alignment;
++
++      char *NewBuffer;
++#if defined(_MSC_VER)
++      NewBuffer = _aligned_malloc((size_t) NewCapacity, (size_t) Alignment);
++      assert(NewBuffer && "_aligned_malloc failed!");
++#else
++      int R = posix_memalign((void**) &NewBuffer, Alignment, NewCapacity);
++
++      assert((R == 0) && "posix_memalign failed!");
++      assert(NewBuffer && "Memory allocation failed!");
++#endif
++
++      if ((Buffer != 0) && (BufferSize > 0))
++        (void) std::memcpy(NewBuffer, Buffer, BufferSize);
++
++      if ((Buffer != 0) && (BufferSize > 0))
++        std::free(static_cast<void*>(Buffer));
++
+       Buffer = NewBuffer;
+       BufferCapacity = NewCapacity;
+     }
+-    
+-    memcpy(Buffer + BufferSize, Start, End - Start);
++
++    (void) std::memcpy(Buffer + BufferSize, Start, End - Start);
+     BufferSize += End-Start;
+   }
+-  
++
+   /// \brief Save a source location to the given buffer.
+   void SaveSourceLocation(SourceLocation Loc, char *&Buffer,
+                           unsigned &BufferSize, unsigned &BufferCapacity) {
+@@ -469,7 +488,7 @@
+            reinterpret_cast<char *>(&Raw) + sizeof(unsigned),
+            Buffer, BufferSize, BufferCapacity);
+   }
+-  
++
+   /// \brief Save a pointer to the given buffer.
+   void SavePointer(void *Ptr, char *&Buffer, unsigned &BufferSize,
+                    unsigned &BufferCapacity) {
+@@ -480,13 +499,13 @@
+ }
+ 
+ NestedNameSpecifierLocBuilder::
+-NestedNameSpecifierLocBuilder(const NestedNameSpecifierLocBuilder &Other) 
++NestedNameSpecifierLocBuilder(const NestedNameSpecifierLocBuilder &Other)
+   : Representation(Other.Representation), Buffer(nullptr),
+     BufferSize(0), BufferCapacity(0)
+ {
+   if (!Other.Buffer)
+     return;
+-  
++
+   if (Other.BufferCapacity == 0) {
+     // Shallow copy is okay.
+     Buffer = Other.Buffer;
+diff: tools/clang/lib/AST/Stmt.cpp: No such file or directory
+--- tools/clang/lib/AST/TemplateBase.cpp	2015-12-29 13:15:14.000000000 -0500
++++ tools/clang/lib/AST/TemplateBase.cpp	2016-05-08 23:19:20.561431458 -0400
+@@ -71,6 +71,7 @@
+ 
+ TemplateArgument::TemplateArgument(ASTContext &Ctx, const llvm::APSInt &Value,
+                                    QualType Type) {
++  (void) std::memset(Buffer, 0, sizeof(Buffer));
+   Integer.Kind = Integral;
+   // Copy the APSInt value into our decomposed form.
+   Integer.BitWidth = Value.getBitWidth();
+@@ -78,9 +79,9 @@
+   // If the value is large, we have to get additional memory from the ASTContext
+   unsigned NumWords = Value.getNumWords();
+   if (NumWords > 1) {
+-    void *Mem = Ctx.Allocate(NumWords * sizeof(uint64_t));
++    void *Mem = Ctx.Allocate(NumWords * sizeof(uint64_t), alignof(uint64_t));
+     std::memcpy(Mem, Value.getRawData(), NumWords * sizeof(uint64_t));
+-    Integer.pVal = static_cast<uint64_t *>(Mem);
++    Integer.pVal = reinterpret_cast<uint64_t *>(Mem);
+   } else {
+     Integer.VAL = Value.getZExtValue();
+   }
+@@ -420,7 +421,9 @@
+ //===----------------------------------------------------------------------===//
+ 
+ TemplateArgumentLocInfo::TemplateArgumentLocInfo() {
+-  memset((void*)this, 0, sizeof(TemplateArgumentLocInfo));
++  (void) std::memset(Buffer, 0, sizeof(Buffer));
++  Expression = nullptr;
++  Declarator = nullptr;
+ }
+ 
+ SourceRange TemplateArgumentLoc::getSourceRange() const {
+--- tools/clang/lib/AST/Type.cpp	2016-01-09 07:53:17.000000000 -0500
++++ tools/clang/lib/AST/Type.cpp	2016-05-08 23:19:20.562431482 -0400
+@@ -2466,7 +2466,10 @@
+     if (Args[I].containsUnexpandedParameterPack())
+       setContainsUnexpandedParameterPack();
+ 
+-    new (&getArgBuffer()[I]) TemplateArgument(Args[I]);
++    TemplateArgument *TA = getArgBuffer();
++    TA = &(TA[I]);
++    TA = new (TA) TemplateArgument();
++    *TA = Args[I];
+   }
+ }
+ 
--- a/components/llvm/patches/009-InitPreprocessor.patch	Thu Jul 28 16:15:45 2016 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,69 +0,0 @@
-# The anonymous std::string temporary created by getClangFullRepositoryVersion
-# goes out-of-scope in C++11 because COW std::string is not allowed.
-# I.e. the std::string buffer of the anonymous temporary goes out of scope.
-# Because of this, the buffer referenced by the underlying StringRef in
-# llvm::Twine is invalid as soon as the std::string temporary expires.
-# The tagged clang version string must be created as a data segment global
-# constant via macro, just like all the other clang version macro identifiers.
-# https://llvm.org/bugs/show_bug.cgi?id=24684
---- tools/clang/include/clang/Basic/Version.inc.in	2010-06-25 13:33:46.000000000 -0400
-+++ tools/clang/include/clang/Basic/Version.inc.in	2015-07-05 14:20:27.771128865 -0400
-@@ -4,3 +4,4 @@
- #if @CLANG_HAS_VERSION_PATCHLEVEL@
- #define CLANG_VERSION_PATCHLEVEL @CLANG_VERSION_PATCHLEVEL@
- #endif
-+#define CLANG_VERSION_TAGGED_STRING @CLANG_VERSION_TAGGED_STRING@
---- tools/clang/include/clang/Basic/Makefile	2014-03-31 09:14:44.000000000 -0400
-+++ tools/clang/include/clang/Basic/Makefile	2015-07-05 14:19:58.972485543 -0400
-@@ -16,8 +16,18 @@
- 
- INPUT_TDS = $(wildcard $(PROJ_SRC_DIR)/Diagnostic*.td)
- 
-+SVN_OR_RC :=
-+
- # Compute the Clang version from the LLVM version, unless specified explicitly.
- ifndef CLANG_VERSION
-+ifeq ($(LLVMVersion), $(findstring svn, $(LLVMVersion)), svn)
-+  SVN_OR_RC := "svn"
-+endif
-+
-+ifeq ($(LLVMVersion), $(findstring rc, $(LLVMVersion)), rc)
-+  SVN_OR_RC := "rc"
-+endif
-+
- CLANG_VERSION := $(subst svn,,$(LLVMVersion))
- CLANG_VERSION := $(subst rc,,$(CLANG_VERSION))
- endif
-@@ -26,6 +36,14 @@
- CLANG_VERSION_MAJOR := $(word 1,$(CLANG_VERSION_COMPONENTS))
- CLANG_VERSION_MINOR := $(word 2,$(CLANG_VERSION_COMPONENTS))
- CLANG_VERSION_PATCHLEVEL := $(word 3,$(CLANG_VERSION_COMPONENTS))
-+CLANG_VERSION_TAGGED_STRING :=
-+
-+ifeq ($(SVN_OR_RC),)
-+CLANG_VERSION_TAGGED_STRING := "\"\(tags/RELEASE_$(CLANG_VERSION_MAJOR)$(CLANG_VERSION_MINOR)$(CLANG_VERSION_PATCHLEVEL)/final\)\""
-+else
-+CLANG_VERSION_TAGGED_STRING := "\"\(tags/RELEASE_$(CLANG_VERSION_MAJOR)$(CLANG_VERSION_MINOR)$(CLANG_VERSION_PATCHLEVEL)/$(SVN_OR_RC)\)\""
-+endif
-+
- ifeq ($(CLANG_VERSION_PATCHLEVEL),)
- CLANG_HAS_VERSION_PATCHLEVEL := 0
- else
-@@ -67,4 +85,5 @@
- 	           -e "s#@CLANG_VERSION_MINOR@#$(CLANG_VERSION_MINOR)#g" \
- 	           -e "s#@CLANG_VERSION_PATCHLEVEL@#$(CLANG_VERSION_PATCHLEVEL)#g" \
- 	           -e "s#@CLANG_HAS_VERSION_PATCHLEVEL@#$(CLANG_HAS_VERSION_PATCHLEVEL)#g" \
-+	           -e "s#@CLANG_VERSION_TAGGED_STRING@#$(CLANG_VERSION_TAGGED_STRING:' '='')#g" \
- 	           $< > $@
---- tools/clang/lib/Frontend/InitPreprocessor.cpp	2015-04-27 04:12:42.000000000 -0400
-+++ tools/clang/lib/Frontend/InitPreprocessor.cpp	2015-07-05 14:24:20.804334574 -0400
-@@ -470,8 +470,7 @@
-   Builder.defineMacro("__clang_patchlevel__", "0");
- #endif
-   Builder.defineMacro("__clang_version__", 
--                      "\"" CLANG_VERSION_STRING " "
--                      + getClangFullRepositoryVersion() + "\"");
-+                      "\"" CLANG_VERSION_STRING " " CLANG_VERSION_TAGGED_STRING "\"");
- #undef TOSTR
- #undef TOSTR2
-   if (!LangOpts.MSVCCompat) {
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/009-solaris-clang-libclangSema.patch	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,149 @@
+# 22902355 clang CodeGen is affected by 22902339
+# 3.9.X upstream.
+--- tools/clang/include/clang/Sema/AttributeList.h	2015-12-02 12:07:30.000000000 -0500
++++ tools/clang/include/clang/Sema/AttributeList.h	2016-05-08 23:19:20.555431312 -0400
+@@ -475,6 +475,27 @@
+   unsigned getSemanticSpelling() const;
+ };
+ 
++static_assert(
++  llvm::AlignOf<AttributeList>::Alignment >=
++  llvm::AlignOf<ArgsUnion>::Alignment,
++  "Alignment is insufficient for objects appended to AttributeList");
++static_assert(
++  llvm::AlignOf<ArgsUnion>::Alignment >=
++  llvm::AlignOf<AvailabilityChange>::Alignment,
++  "Alignment is insufficient for objects appended to AttributeList");
++static_assert(
++  llvm::AlignOf<ArgsUnion>::Alignment >=
++  llvm::AlignOf<AttributeList::TypeTagForDatatypeData>::Alignment,
++  "Alignment is insufficient for objects appended to AttributeList");
++static_assert(
++  llvm::AlignOf<AttributeList>::Alignment >=
++  llvm::AlignOf<ParsedType>::Alignment,
++  "Alignment is insufficient for objects appended to AttributeList");
++static_assert(
++  llvm::AlignOf<AttributeList>::Alignment >=
++  llvm::AlignOf<AttributeList::PropertyData>::Alignment,
++  "Alignment is insufficient for objects appended to AttributeList");
++
+ /// A factory, from which one makes pools, from which one creates
+ /// individual attributes which are deallocated with the pool.
+ ///
+--- tools/clang/include/clang/Sema/CodeCompleteConsumer.h	2015-07-07 02:20:19.000000000 -0400
++++ tools/clang/include/clang/Sema/CodeCompleteConsumer.h	2016-05-08 23:19:20.555431312 -0400
+@@ -494,6 +494,14 @@
+   /// which is mainly useful for debugging.
+   std::string getAsString() const;
+ };
++static_assert(
++    llvm::AlignOf<CodeCompletionString>::Alignment >=
++        llvm::AlignOf<CodeCompletionString::Chunk>::Alignment,
++    "Alignment is insufficient for objects appended to CodeCompletionString");
++static_assert(
++    llvm::AlignOf<CodeCompletionString::Chunk>::Alignment >=
++        llvm::AlignOf<const char *>::Alignment,
++    "Alignment is insufficient for objects appended to CodeCompletionString");
+ 
+ /// \brief An allocator used specifically for the purpose of code completion.
+ class CodeCompletionAllocator : public llvm::BumpPtrAllocator {
+--- tools/clang/include/clang/Sema/ParsedTemplate.h	2015-06-22 19:07:51.000000000 -0400
++++ tools/clang/include/clang/Sema/ParsedTemplate.h	2016-05-08 23:19:20.555431312 -0400
+@@ -205,6 +205,10 @@
+       free(this); 
+     }
+   };
++  static_assert(
++      llvm::AlignOf<TemplateIdAnnotation>::Alignment >=
++          llvm::AlignOf<ParsedTemplateArgument>::Alignment,
++      "Alignment is insufficient for objects appended to TemplateIdAnnotation");
+ 
+   /// Retrieves the range of the given template parameter lists.
+   SourceRange getTemplateParamsRange(TemplateParameterList const *const *Params,
+--- tools/clang/lib/Sema/SemaExceptionSpec.cpp	2015-12-18 16:45:41.000000000 -0500
++++ tools/clang/lib/Sema/SemaExceptionSpec.cpp	2016-05-08 23:19:20.576431823 -0400
+@@ -998,9 +998,8 @@
+   case Expr::LambdaExprClass: {
+     const LambdaExpr *Lambda = cast<LambdaExpr>(E);
+     CanThrowResult CT = CT_Cannot;
+-    for (LambdaExpr::const_capture_init_iterator
+-             Cap = Lambda->capture_init_begin(),
+-             CapEnd = Lambda->capture_init_end();
++    for (LambdaExpr::const_capture_init_iterator Cap =
++         Lambda->capture_init_begin(), CapEnd = Lambda->capture_init_end();
+          Cap != CapEnd; ++Cap)
+       CT = mergeCanThrow(CT, canThrow(*Cap));
+     return CT;
+--- tools/clang/lib/Sema/TypeLocBuilder.cpp	2014-05-26 02:22:03.000000000 -0400
++++ tools/clang/lib/Sema/TypeLocBuilder.cpp	2016-05-08 23:19:20.576431823 -0400
+@@ -13,6 +13,8 @@
+ //===----------------------------------------------------------------------===//
+ 
+ #include "TypeLocBuilder.h"
++#include <cstring>
++#include <stdlib.h>
+ 
+ using namespace clang;
+ 
+@@ -46,14 +48,35 @@
+   assert(NewCapacity > Capacity);
+ 
+   // Allocate the new buffer and copy the old data into it.
+-  char *NewBuffer = new char[NewCapacity];
++  char *NewBuffer;
++
++#if defined(_MSC_VER)
++  NewBuffer = _aligned_malloc(NewCapacity, (size_t) BufferMaxAlignment);
++  assert(NewBuffer && "_aligned_malloc failed!");
++  if (!NewBuffer) {
++    llvm::errs() << __PRETTY_FUNCTION__ << ": _aligned_malloc failed!\n";
++    abort();
++  }
++#else
++  int R = posix_memalign((void**) &NewBuffer,
++                         (size_t) BufferMaxAlignment, NewCapacity);
++  assert((R == 0) && "posix_memalign failed!");
++  assert(NewBuffer && "posix_memalign failed!");
++  if ((R != 0) || (!NewBuffer)) {
++    llvm::errs() << __PRETTY_FUNCTION__ << ": posix_memalign failed!\n";
++    abort();
++  }
++#endif
++
++  (void) std::memset(NewBuffer, 0, NewCapacity);
++
+   unsigned NewIndex = Index + NewCapacity - Capacity;
+-  memcpy(&NewBuffer[NewIndex],
+-         &Buffer[Index],
+-         Capacity - Index);
++  (void) std::memcpy(&NewBuffer[NewIndex],
++                     &Buffer[Index],
++                     Capacity - Index);
+ 
+   if (Buffer != InlineBuffer.buffer)
+-    delete[] Buffer;
++    std::free(Buffer);
+ 
+   Buffer = NewBuffer;
+   Capacity = NewCapacity;
+--- tools/clang/lib/Sema/TypeLocBuilder.h	2015-06-22 19:07:51.000000000 -0400
++++ tools/clang/lib/Sema/TypeLocBuilder.h	2016-05-08 23:19:20.577431847 -0400
+@@ -39,7 +39,7 @@
+ #endif
+     
+   /// The inline buffer.
+-  enum { BufferMaxAlignment = llvm::AlignOf<void*>::Alignment };
++  enum { BufferMaxAlignment = llvm::AlignOf<uint64_t>::Alignment };
+   llvm::AlignedCharArray<BufferMaxAlignment, InlineCapacity> InlineBuffer;
+   unsigned NumBytesAtAlign4, NumBytesAtAlign8;
+ 
+@@ -52,7 +52,7 @@
+ 
+   ~TypeLocBuilder() {
+     if (Buffer != InlineBuffer.buffer)
+-      delete[] Buffer;
++      std::free(Buffer);
+   }
+ 
+   /// Ensures that this buffer has at least as much capacity as described.
+
--- a/components/llvm/patches/010-linker-mapfiles.patch	Thu Jul 28 16:15:45 2016 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,130 +0,0 @@
-# 1. Enable the linker map files provided by clang/llvm for symbol
-# scope and visibility in shared libraries.
-# 2. We must use our own linker map file for compatibility with
-# the GNU linkers and GNU Binutils (libbfd).
-# Solaris autoconf-based build.
-# https://llvm.org/bugs/show_bug.cgi?id=24641
---- Makefile.rules	2015-07-17 19:12:32.515872699 -0700
-+++ Makefile.rules	2015-07-17 19:17:40.294355307 -0700
-@@ -643,6 +643,7 @@
-     endif
-     ifeq ($(HOST_OS), $(filter $(HOST_OS), SunOS))
-       LD.Flags += -Wl,-z -Wl,discard-unused=sections
-+      LD.Flags += -Wl,-M -Wl,$(PROJ_SRC_ROOT)/mapfiles/map.gnu-sections
-     endif
-   endif
- endif
-@@ -655,6 +656,10 @@
-   ifneq ($(HOST_OS), Darwin)
-     ifdef TOOLNAME
-       LD.Flags += $(RPATH) -Wl,'$$ORIGIN/../lib'
-+      ifeq ($(HOST_OS), $(filter $(HOST_OS), SunOS))
-+        LD.Flags += -Wl,-z -Wl,discard-unused=sections
-+        LD.Flags += -Wl,-M -Wl,$(PROJ_SRC_ROOT)/mapfiles/map.gnu-sections
-+      endif
-     endif
-   else
-     ifneq ($(DARWIN_MAJVERS),4)
-@@ -1122,11 +1127,26 @@
- clean-local::
- 	-$(Verb) $(RM) -f $(NativeExportsFile)
- else
-+ifeq ($(HOST_OS), $(filter $(HOST_OS), SunOS))
-+# Solaris ld requires 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
- # Default behavior: just use the exports file verbatim.
- NativeExportsFile := $(EXPORTED_SYMBOL_FILE)
- endif
- endif
- endif
-+endif
- 
- # Now add the linker command-line options to use the native export file.
- 
-@@ -1146,6 +1166,11 @@
- SharedLinkOptions += $(NativeExportsFile)
- endif
- 
-+# Solaris
-+ifeq ($(HOST_OS), $(filter $(HOST_OS), SunOS))
-+LLVMLibsOptions += -Wl,-M -Wl,$(NativeExportsFile)
-+endif
-+
- endif
- 
- ###############################################################################
---- /dev/null	2015-07-08 19:15:05.000000000 -0700
-+++ mapfiles/map.gnu-sections	2015-07-08 19:13:41.905920797 -0700
-@@ -0,0 +1,61 @@
-+$mapfile_version 2
-+
-+# Emulate the rules used by the GNU ld and gold linkers for merging input
-+# sections into output sections in executables and shared objects. From
-+# Ian Lance Taylor and Cary Coutant.
-+
-+# gcc 4.3 generates the following sorts of section names when it
-+# needs a section name specific to a function:
-+#   .text.FN
-+#   .rodata.FN
-+#   .sdata2.FN
-+#   .data.FN
-+#   .data.rel.FN
-+#   .data.rel.local.FN
-+#   .data.rel.ro.FN
-+#   .data.rel.ro.local.FN
-+#   .sdata.FN
-+#   .bss.FN
-+#   .sbss.FN
-+#   .tdata.FN
-+#   .tbss.FN
-+#
-+# The GNU linker maps all of those to the part before the .FN,
-+# except that .data.rel.local.FN is mapped to .data, and
-+# .data.rel.ro.local.FN is mapped to .data.rel.ro.  The sections
-+# beginning with .data.rel.ro.local are grouped together.
-+#
-+# For an anonymous namespace, the string FN can contain a '.'.
-+#
-+# Also of interest: .rodata.strN.N, .rodata.cstN, both of which the
-+# GNU linker maps to .rodata.
-+
-+$if _ET_DYN || _ET_EXEC
-+
-+LOAD_SEGMENT text {
-+	ASSIGN_SECTION {
-+		IS_NAME = MATCH(g/.data.rel.local.*/);
-+		FLAGS = ALLOC !WRITE;
-+		OUTPUT_SECTION { NAME = .data };
-+	};
-+	ASSIGN_SECTION {
-+		IS_NAME = MATCH(r/^\.(text|rodata|sdata2|data\.rel\.ro|data\.rel|data|sdata|bss|sbss|tdata|tbss)\./);
-+		FLAGS = ALLOC !WRITE;
-+		OUTPUT_SECTION { NAME = MATCHREF(/.${n1}/) };
-+	};
-+};
-+
-+LOAD_SEGMENT data {
-+	ASSIGN_SECTION {
-+		IS_NAME = MATCH(g/.data.rel.local.*/);
-+		FLAGS = ALLOC WRITE;
-+		OUTPUT_SECTION { NAME = .data };
-+	};
-+	ASSIGN_SECTION {
-+		IS_NAME = MATCH(r/^\.(text|rodata|sdata2|data\.rel\.ro|data\.rel|data|sdata|bss|sbss|tdata|tbss)\./);
-+		FLAGS = ALLOC WRITE;
-+		OUTPUT_SECTION { NAME = MATCHREF(/.${n1}/) };
-+	};
-+};
-+
-+$endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/010-solaris-clang-libclangBasic.patch	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,304 @@
+# 23701635 clang produces amd64 opcodes, but calls 32-bit assembler by default
+# 3.9.X for upstream.
+--- tools/clang/include/clang/Basic/LangOptions.def	2016-01-06 08:42:12.000000000 -0500
++++ tools/clang/include/clang/Basic/LangOptions.def	2016-05-08 23:19:20.551431215 -0400
+@@ -140,6 +140,8 @@
+               "default struct packing maximum alignment")
+ VALUE_LANGOPT(MaxTypeAlign  , 32, 0,
+               "default maximum alignment for types")
++VALUE_LANGOPT(GXXABIVersion , 32, 0,
++              "Use specified GNU C++ Standard Library ABI version")
+ VALUE_LANGOPT(PICLevel    , 2, 0, "__PIC__ level")
+ VALUE_LANGOPT(PIELevel    , 2, 0, "__PIE__ level")
+ LANGOPT(GNUInline         , 1, 0, "GNU inline semantics")
+###
+--- tools/clang/include/clang/Basic/Version.inc.in	2010-06-25 13:33:46.000000000 -0400
++++ tools/clang/include/clang/Basic/Version.inc.in	2016-05-08 23:19:20.552431239 -0400
+@@ -4,3 +4,4 @@
+ #if @CLANG_HAS_VERSION_PATCHLEVEL@
+ #define CLANG_VERSION_PATCHLEVEL @CLANG_VERSION_PATCHLEVEL@
+ #endif
++#define CLANG_VERSION_TAGGED_STRING @CLANG_VERSION_TAGGED_STRING@
+###
+--- tools/clang/include/clang/Basic/TargetInfo.h	2015-11-17 16:15:28.000000000 -0800
++++ tools/clang/include/clang/Basic/TargetInfo.h	2016-05-13 19:02:00.975115645 -0700
+@@ -86,11 +86,11 @@
+   mutable StringRef PlatformName;
+   mutable VersionTuple PlatformMinVersion;
+ 
+-  unsigned HasAlignMac68kSupport : 1;
+-  unsigned RealTypeUsesObjCFPRet : 3;
+-  unsigned ComplexLongDoubleUsesFP2Ret : 1;
++  bool HasAlignMac68kSupport;
++  unsigned RealTypeUsesObjCFPRet;
++  bool ComplexLongDoubleUsesFP2Ret;
+ 
+-  unsigned HasBuiltinMSVaList : 1;
++  bool HasBuiltinMSVaList;
+ 
+   // TargetInfo Constructor.  Default initializes all fields.
+   TargetInfo(const llvm::Triple &T);
+###
+--- tools/clang/lib/Basic/IdentifierTable.cpp	2015-10-21 23:52:15.000000000 -0400
++++ tools/clang/lib/Basic/IdentifierTable.cpp	2016-05-08 23:19:20.562431482 -0400
+@@ -393,6 +393,11 @@
+     Profile(ID, keyword_begin(), getNumArgs());
+   }
+ };
++static_assert(
++    llvm::AlignOf<MultiKeywordSelector>::Alignment >=
++        llvm::AlignOf<IdentifierInfo *>::Alignment,
++    "Insufficient alignment for objects appended to MultiKeywordSelector");
++
+ } // end namespace clang.
+ 
+ unsigned Selector::getNumArgs() const {
+###
+--- tools/clang/lib/Basic/Targets.cpp	2016-02-19 08:40:14.000000000 -0900
++++ tools/clang/lib/Basic/Targets.cpp	2016-07-06 07:39:20.069419785 -0800
+@@ -29,10 +29,11 @@
+ #include "llvm/MC/MCSectionMachO.h"
+ #include "llvm/Support/ErrorHandling.h"
+ #include "llvm/Support/TargetParser.h"
++using namespace clang;
++
+ #include <algorithm>
+ #include <memory>
+-
+-using namespace clang;
++#include <string>
+ 
+ //===----------------------------------------------------------------------===//
+ //  Common code shared among targets.
+@@ -618,34 +619,206 @@
+ // Solaris target
+ template<typename Target>
+ class SolarisTargetInfo : public OSTargetInfo<Target> {
++private:
++  std::string ABI;
++  std::string CPU;
++
+ protected:
+-  void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
+-                    MacroBuilder &Builder) const override {
++  virtual void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
++                            MacroBuilder &Builder) const override {
+     DefineStd(Builder, "sun", Opts);
+     DefineStd(Builder, "unix", Opts);
+     Builder.defineMacro("__ELF__");
+     Builder.defineMacro("__svr4__");
+     Builder.defineMacro("__SVR4");
+-    // Solaris headers require _XOPEN_SOURCE to be set to 600 for C99 and
+-    // newer, but to 500 for everything else.  feature_test.h has a check to
+-    // ensure that you are not using C99 with an old version of X/Open or C89
+-    // with a new version.
+-    if (Opts.C99)
++    Builder.defineMacro("__SunOS", "1");
++
++    Builder.defineMacro("__EXTENSIONS__", "1");
++
++    if (Opts.POSIXThreads) {
++      Builder.defineMacro("_REENTRANT");
++      Builder.defineMacro("__GTHREADS", "1");
++    }
++
++    if (Opts.C99) {
+       Builder.defineMacro("_XOPEN_SOURCE", "600");
+-    else
++      Builder.defineMacro("_XPG6", "1");
++      Builder.defineMacro("__STDC_VERSION__", "199901L");
++      Builder.defineMacro("_STDC_C99", "1");
++      Builder.defineMacro("__C99FEATURES__", "1");
++    }
++
++    if (Opts.CPlusPlus11) {
++      Builder.defineMacro("__cplusplus", "201103L");
++      Builder.defineMacro("_XOPEN_SOURCE", "600");
++      Builder.defineMacro("_XPG6", "1");
++    } else if (Opts.CPlusPlus14) {
++      Builder.defineMacro("__cplusplus", "201402L");
++      Builder.defineMacro("_XOPEN_SOURCE", "700");
++      Builder.defineMacro("_XPG7", "1");
++    }
++
++    if (Opts.CPlusPlus || Opts.CPlusPlus11 || Opts.CPlusPlus14 ||
++        Opts.CPlusPlus1z) {
++      Builder.defineMacro("__STDCPP_STRICT_POINTER_SAFETY__", "1");
++      Builder.defineMacro("__STDCPP_THREADS__", "1");
++    }
++
++    if (Opts.CPlusPlus11) {
++      Builder.defineMacro("_STDC_C99", "1");
++      Builder.defineMacro("__STDC_VERSION__", "199901L");
++      Builder.defineMacro("__C99FEATURES__", "1");
++      Builder.defineMacro("__STDC_ISO_10646__", "201011L");
++      Builder.defineMacro("__STDC_MB_MIGHT_NEQ_WC__", "1");
++      Builder.defineMacro("__STDC_LIB_EXT1__", "201112L");
++    } else if (Opts.C11 || Opts.CPlusPlus14) {
++      Builder.defineMacro("__STDC_HOSTED__", "1");
++      Builder.defineMacro("__STDC_VERSION__", "201112L");
++      Builder.defineMacro("_STDC_C11", "1");
++      Builder.defineMacro("_STDC_C11_BCI", "1");
++      Builder.defineMacro("__STDC_ISO_10646__", "201011L");
++      Builder.defineMacro("__STDC_MB_MIGHT_NEQ_WC__", "1");
++      Builder.defineMacro("__STDC_LIB_EXT1__", "201112L");
++      Builder.defineMacro("__STDC_UTF_16__", "1");
++      Builder.defineMacro("__STDC_UTF_32__", "1");
++      Builder.defineMacro("__XPG7_THREAD_MODEL__", "1");
++
++      if (Opts.C11) {
++        Builder.defineMacro("__STDC_ANALYZABLE", "1");
++        Builder.defineMacro("__STDC_IEC_559__", "1");
++        Builder.defineMacro("__STDC_IEC_559_COMPLEX__", "1");
++      }
++    } else if (Opts.CPlusPlus1z) {
++      // This is bogus until C++17 is actually ratified,
++      // but we need something to identify C++17 for now.
++      Builder.defineMacro("__cplusplus", "20171231L");
++      Builder.defineMacro("__STDC_VERSION__", "201112L");
++      Builder.defineMacro("_STDC_C11", "1");
++      Builder.defineMacro("_STDC_C11_BCI", "1");
++      Builder.defineMacro("__XPG7_THREAD_MODEL__", "1");
++      Builder.defineMacro("_XOPEN_SOURCE", "700");
++      Builder.defineMacro("_XPG7", "1");
++    } else if ((!Opts.C99 && !Opts.C11) ||
++               (!Opts.CPlusPlus && !Opts.CPlusPlus11 &&
++                !Opts.CPlusPlus14 && !Opts.CPlusPlus1z)) {
+       Builder.defineMacro("_XOPEN_SOURCE", "500");
+-    if (Opts.CPlusPlus)
+-      Builder.defineMacro("__C99FEATURES__");
++      Builder.defineMacro("__STDC_VERSION__", "199409L");
++      if (Opts.CPlusPlus && !Opts.CPlusPlus11 && !Opts.CPlusPlus14 &&
++          !Opts.CPlusPlus1z)
++        Builder.defineMacro("__cplusplus", "199711L");
++    }
++
++    if ((Triple.getArchName() == "i386") || (Triple.getArchName() == "sparc"))
+     Builder.defineMacro("_LARGEFILE_SOURCE");
++    else if ((Triple.getArchName() == "x86_64") ||
++             (Triple.getArchName() == "sparcv9"))
+     Builder.defineMacro("_LARGEFILE64_SOURCE");
+-    Builder.defineMacro("__EXTENSIONS__");
+-    Builder.defineMacro("_REENTRANT");
+   }
++
+ public:
+-  SolarisTargetInfo(const llvm::Triple &Triple) : OSTargetInfo<Target>(Triple) {
++  SolarisTargetInfo(const llvm::Triple &Triple)
++    : OSTargetInfo<Target>(Triple),
++    ABI(""), CPU("") {
+     this->UserLabelPrefix = "";
++
++    llvm::Triple::ArchType Arch = Triple.getArch();
++    switch (Arch) {
++    case llvm::Triple::x86:
++    case llvm::Triple::sparc:
++      this->WCharType = this->SignedLong;
++      break;
++    case llvm::Triple::x86_64:
++    case llvm::Triple::sparcv9:
+     this->WCharType = this->SignedInt;
+-    // FIXME: WIntType should be SignedLong
++      break;
++    default:
++      this->WCharType = this->SignedInt;
++      break;
++    }
++  }
++
++  virtual const char *getStaticInitSectionSpecifier() const override {
++    return ".init";
++  }
++
++  virtual bool setCPU(const std::string &Name) {
++    CPU = Name;
++    std::transform(CPU.begin(), CPU.end(), CPU.begin(), ::tolower);
++
++    bool K = llvm::StringSwitch<bool>(Name)
++      .Case("generic", true)
++      .Case("native", true)
++      .Case("sparc4", true)
++      .Case("sparc5", true)
++      .Case("v8plus", true)
++      .Case("v8plusa", true)
++      .Case("v8plusb", true)
++      .Case("v8plusc", true)
++      .Case("v8plusd", true)
++      .Case("v8pluse", true)
++      .Case("v8plusv", true)
++      .Case("v8plusm", true)
++      .Case("v9", true)
++      .Case("v9a", true)
++      .Case("v9b", true)
++      .Case("v9c", true)
++      .Case("v9d", true)
++      .Case("v9e", true)
++      .Case("v9v", true)
++      .Case("v9m", true)
++      .Case("ultrasparc", true)
++      .Case("ultrasparc2", true)
++      .Case("ultrasparc3", true)
++      .Case("ultrasparc4", true)
++      .Case("generic32", true)
++      .Case("generic64", true)
++      .Case("i386", true)
++      .Case("i486", true)
++      .Case("i586", true)
++      .Case("i686", true)
++      .Case("pentium", true)
++      .Case("pentiumpro", true)
++      .Case("pentium2", true)
++      .Case("pentiumii", true)
++      .Case("pentium3", true)
++      .Case("pentiumiii", true)
++      .Case("pentium4", true)
++      .Case("pentiumiv", true)
++      .Case("prescott", true)
++      .Case("nocona", true)
++      .Case("core", true)
++      .Case("core2", true)
++      .Case("corei7", true)
++      .Case("l1om", true)
++      .Case("k1om", true)
++      .Case("k6", true)
++      .Case("k6_2", true)
++      .Case("athlon", true)
++      .Case("opteron", true)
++      .Case("x86-64", true)
++      .Case("X86-64", true)
++      .Case("x86_64", true)
++      .Case("X86_64", true)
++      .Case("k8", true)
++      .Case("amdfam10", true)
++      .Case("bdver1", true)
++      .Case("bdver2", true)
++      .Case("bdver3", true)
++      .Case("bdver4", true)
++      .Case("btver1", true)
++      .Case("btver2", true)
++      .Default(false);
++
++    return K;
++  }
++
++  virtual bool setABI(const std::string &Name) {
++    ABI = Name;
++    std::transform(ABI.begin(), ABI.end(), ABI.begin(), ::tolower);
++    if (ABI.find("itanium") != std::string::npos)
++      return true;
++
++    return false;
+   }
+ };
+ 
+@@ -5893,6 +6066,10 @@
+     case 'N': // Same as 'K' but zext (required for SIMode)
+     case 'O': // The constant 4096
+       return true;
++
++    case 'f':
++      info.setAllowsRegister();
++      return true;
+     }
+     return false;
+   }
--- a/components/llvm/patches/011-gxx-abi-version.patch	Thu Jul 28 16:15:45 2016 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,85 +0,0 @@
-# Add an implementation for -fabi-version=<N> in clang.
-# This is useful and required for testing the GNU C++
-# Standard Library for GCC >= 5.0.
-# https://llvm.org/bugs/show_bug.cgi?id=24685
---- tools/clang/include/clang/Basic/LangOptions.def	2014-12-03 16:53:36.000000000 -0500
-+++ tools/clang/include/clang/Basic/LangOptions.def	2015-07-11 11:35:34.710878157 -0400
-@@ -134,6 +134,8 @@
-               "default struct packing maximum alignment")
- VALUE_LANGOPT(MaxTypeAlign  , 32, 0,
-               "default maximum alignment for types")
-+VALUE_LANGOPT(GXXABIVersion , 32, 0,
-+              "Use specified GNU C++ Standard Library ABI version")
- VALUE_LANGOPT(PICLevel    , 2, 0, "__PIC__ level")
- VALUE_LANGOPT(PIELevel    , 2, 0, "__PIE__ level")
- LANGOPT(GNUInline         , 1, 0, "GNU inline semantics")
---- tools/clang/lib/Frontend/InitPreprocessor.cpp	2015-09-01 06:51:55.849518525 -0700
-+++ tools/clang/lib/Frontend/InitPreprocessor.cpp	2015-09-02 13:53:24.781943196 -0700
-@@ -479,7 +479,31 @@
-     Builder.defineMacro("__GNUC_MINOR__", "2");
-     Builder.defineMacro("__GNUC_PATCHLEVEL__", "1");
-     Builder.defineMacro("__GNUC__", "4");
-+    // GCC provides a number of C++ ABI Versions in:
-+    // ${top_srcdir}/gcc/c-family/c-cppbuiltin.c
-+    // Currently valid GXX ABI Versions are documented here:
-+    // https://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Dialect-Options.html
-+    // clang only supports a subset.
-+    switch (LangOpts.GXXABIVersion) {
-+    default:
-     Builder.defineMacro("__GXX_ABI_VERSION", "1002");
-+      break;
-+    case 4:
-+      Builder.defineMacro("__GXX_ABI_VERSION", "1004");
-+      break;
-+    case 5:
-+      Builder.defineMacro("__GXX_ABI_VERSION", "1005");
-+      break;
-+    case 6:
-+      Builder.defineMacro("__GXX_ABI_VERSION", "1006");
-+      break;
-+    case 7:
-+      Builder.defineMacro("__GXX_ABI_VERSION", "1007");
-+      break;
-+    case 8:
-+      Builder.defineMacro("__GXX_ABI_VERSION", "1008");
-+      break;
-+    }
-   }
- 
-   // Define macros for the C11 / C++11 memory orderings
---- tools/clang/lib/Frontend/CompilerInvocation.cpp	2015-05-04 14:23:43.000000000 -0400
-+++ tools/clang/lib/Frontend/CompilerInvocation.cpp	2015-07-11 15:40:20.580031428 -0400
-@@ -1539,6 +1539,7 @@
-   Opts.EmitAllDecls = Args.hasArg(OPT_femit_all_decls);
-   Opts.PackStruct = getLastArgIntValue(Args, OPT_fpack_struct_EQ, 0, Diags);
-   Opts.MaxTypeAlign = getLastArgIntValue(Args, OPT_fmax_type_align_EQ, 0, Diags);
-+  Opts.GXXABIVersion = getLastArgIntValue(Args, OPT_fabi_version_EQ, 0, Diags);
-   Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
-   Opts.PIELevel = getLastArgIntValue(Args, OPT_pie_level, 0, Diags);
-   Opts.Static = Args.hasArg(OPT_static_define);
---- tools/clang/include/clang/Driver/Options.td	2015-01-26 18:17:18.000000000 -0500
-+++ tools/clang/include/clang/Driver/Options.td	2015-07-11 15:44:39.660620608 -0400
-@@ -574,6 +574,8 @@
- def ffp_contract : Joined<["-"], "ffp-contract=">, Group<f_Group>,
-   Flags<[CC1Option]>, HelpText<"Form fused FP ops (e.g. FMAs): fast (everywhere)"
-   " | on (according to FP_CONTRACT pragma, default) | off (never fuse)">;
-+def fabi_version_EQ : Joined<["-"], "fabi-version=">, Group<f_Group>,
-+  Flags<[CC1Option]>, HelpText<"Use specified GNU C++ ABI version">;
- 
- def ffor_scope : Flag<["-"], "ffor-scope">, Group<f_Group>;
- def fno_for_scope : Flag<["-"], "fno-for-scope">, Group<f_Group>;
---- tools/clang/lib/Driver/Tools.cpp	2015-02-03 17:57:34.000000000 -0500
-+++ tools/clang/lib/Driver/Tools.cpp	2015-07-11 23:36:17.198486944 -0400
-@@ -2812,6 +2812,12 @@
-     CmdArgs.push_back(A->getValue());
-   }
- 
-+  if (Arg *A = Args.getLastArg(options::OPT_fabi_version_EQ)) {
-+    StringRef v = A->getValue();
-+    CmdArgs.push_back(Args.MakeArgString("-fabi-version=" + v));
-+    A->claim();
-+  }
-+
-   if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
-                                options::OPT_freg_struct_return)) {
-     if (getToolChain().getArch() != llvm::Triple::x86) {
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/011-solaris-clang-libclangCodeGen.patch	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,631 @@
+# 24306550 clang crashes in llvm::Twine::toStringRef
+# 22902355 clang CodeGen is affected by 22902339
+# 3.9.X for upstream.
+--- tools/clang/include/clang/CodeGen/CGFunctionInfo.h	2015-11-23 17:04:44.000000000 -0500
++++ tools/clang/include/clang/CodeGen/CGFunctionInfo.h	2016-05-08 23:19:20.553431263 -0400
+@@ -334,11 +334,13 @@
+ /// CGFunctionInfo - Class to encapsulate the information about a
+ /// function definition.
+ class CGFunctionInfo : public llvm::FoldingSetNode {
++public:
+   struct ArgInfo {
+     CanQualType type;
+     ABIArgInfo info;
+   };
+ 
++private:
+   /// The LLVM::CallingConv to use for this function (as specified by the
+   /// user).
+   unsigned CallingConvention : 8;
+@@ -508,6 +510,10 @@
+     }
+   }
+ };
++static_assert(
++    llvm::AlignOf<CGFunctionInfo>::Alignment >=
++        llvm::AlignOf<CGFunctionInfo::ArgInfo>::Alignment,
++    "Alignment is insufficient for objects appended to CGFunctionInfo");
+ 
+ /// CGCalleeInfo - Class to encapsulate the information about a callee to be
+ /// used during the generation of call/invoke instructions.
+###
+--- tools/clang/lib/CodeGen/CGCleanup.h	2015-12-12 00:39:21.000000000 -0500
++++ tools/clang/lib/CodeGen/CGCleanup.h	2016-05-08 23:19:20.564431531 -0400
+@@ -233,6 +233,10 @@
+   }
+ };
+ 
++static_assert(llvm::AlignOf<EHCatchScope>::Alignment >=
++              llvm::AlignOf<EHCatchScope::Handler *>::Alignment,
++              "Alignment is insufficient for objects appended to EHCatchScope");
++
+ /// A cleanup scope which generates the cleanup blocks lazily.
+ class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) EHCleanupScope : public EHScope {
+   /// The nearest normal cleanup scope enclosing this one.
+@@ -473,6 +477,17 @@
+     return scope->getKind() == Filter;
+   }
+ };
++// Assert objects tacked on the end of EHCleanupScope won't be
++// misaligned.  NOTE: there's actually a bunch of different data
++// classes tacked on, so let's just ensure alignment good enough for
++// uint64_t bytes.
++static_assert(llvm::AlignOf<EHCleanupScope>::Alignment >=
++                  llvm::AlignOf<uint64_t>::Alignment,
++              "");
++static_assert(
++    llvm::AlignOf<EHFilterScope>::Alignment >=
++        llvm::AlignOf<llvm::Value *>::Alignment,
++    "Alignment is insufficient for objects appended to EHFilterScope");
+ 
+ /// An exceptions scope which calls std::terminate if any exception
+ /// reaches it.
+###
+--- tools/clang/lib/CodeGen/CGDeclCXX.cpp	2015-11-30 17:10:48.000000000 -0800
++++ tools/clang/lib/CodeGen/CGDeclCXX.cpp	2016-07-16 22:05:01.093846960 -0700
+@@ -23,6 +23,8 @@
+ using namespace clang;
+ using namespace CodeGen;
+ 
++static unsigned InitPriority = 65535;
++
+ static void EmitDeclInit(CodeGenFunction &CGF, const VarDecl &D,
+                          ConstantAddress DeclPtr) {
+   assert(D.hasGlobalStorage() && "VarDecl must have global storage!");
+@@ -187,21 +189,21 @@
+                                                   llvm::Constant *dtor,
+                                                   llvm::Constant *addr) {
+   // Get the destructor function type, void(*)(void).
+-  llvm::FunctionType *ty = llvm::FunctionType::get(CGM.VoidTy, false);
+-  SmallString<256> FnName;
++  llvm::FunctionType *FTy = llvm::FunctionType::get(CGM.VoidTy, false);
++  SmallString<512> FnName;
+   {
+     llvm::raw_svector_ostream Out(FnName);
+     CGM.getCXXABI().getMangleContext().mangleDynamicAtExitDestructor(&VD, Out);
+   }
+ 
+   const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
+-  llvm::Function *fn = CGM.CreateGlobalInitOrDestructFunction(ty, FnName.str(),
+-                                                              FI,
++  llvm::Function *Fn =
++    CGM.CreateGlobalInitOrDestructFunction(FTy, FnName.str(), FI,
+                                                               VD.getLocation());
+ 
+   CodeGenFunction CGF(CGM);
+ 
+-  CGF.StartFunction(&VD, CGM.getContext().VoidTy, fn, FI, FunctionArgList());
++  CGF.StartFunction(&VD, CGM.getContext().VoidTy, Fn, FI, FunctionArgList());
+ 
+   llvm::CallInst *call = CGF.Builder.CreateCall(dtor, addr);
+  
+@@ -212,7 +214,7 @@
+ 
+   CGF.FinishFunction();
+ 
+-  return fn;
++  return Fn;
+ }
+ 
+ /// Register a global destructor using the C atexit runtime function.
+@@ -226,12 +228,12 @@
+   llvm::FunctionType *atexitTy =
+     llvm::FunctionType::get(IntTy, dtorStub->getType(), false);
+ 
+-  llvm::Constant *atexit =
++  llvm::Constant *atExit =
+     CGM.CreateRuntimeFunction(atexitTy, "atexit");
+-  if (llvm::Function *atexitFn = dyn_cast<llvm::Function>(atexit))
++  if (llvm::Function *atexitFn = dyn_cast<llvm::Function>(atExit))
+     atexitFn->setDoesNotThrow();
+ 
+-  EmitNounwindRuntimeCall(atexit, dtorStub);
++  EmitNounwindRuntimeCall(atExit, dtorStub);
+ }
+ 
+ void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D,
+@@ -248,17 +250,33 @@
+   CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr, PerformInit);
+ }
+ 
+-llvm::Function *CodeGenModule::CreateGlobalInitOrDestructFunction(
+-    llvm::FunctionType *FTy, const Twine &Name, const CGFunctionInfo &FI,
+-    SourceLocation Loc, bool TLS) {
++llvm::Function*
++CodeGenModule::CreateGlobalInitOrDestructFunction(llvm::FunctionType *FTy,
++                                                  const Twine &Name,
++                                                  const CGFunctionInfo &FI,
++                                                  SourceLocation Loc,
++                                                  bool TLS) {
+   llvm::Function *Fn =
+     llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
+                            Name, &getModule());
+-  if (!getLangOpts().AppleKext && !TLS) {
++
+     // Set the section if needed.
+-    if (const char *Section = getTarget().getStaticInitSectionSpecifier())
++  if (!getLangOpts().AppleKext && !TLS) {
++    if (const char *Section = getTarget().getStaticInitSectionSpecifier()) {
++      if (getTriple().getOS() == llvm::Triple::Solaris) {
++        std::string FNm = Fn->getName().str();
++
++        if (!CodeGenOpts.UseInitArray) {
++          if (FNm.find("_GLOBAL__sub_I_") != std::string::npos)
++            Fn->setSection(Section);
++          else if (FNm.find("_GLOBAL__I_") != std::string::npos)
+       Fn->setSection(Section);
+   }
++      } else {
++        Fn->setSection(Section);
++      }
++    }
++  }
+ 
+   SetInternalFunctionAttributes(nullptr, Fn, FI);
+ 
+@@ -267,6 +285,8 @@
+   if (!getLangOpts().Exceptions)
+     Fn->setDoesNotThrow();
+ 
++  // Solaris does not support the Sanitizer Libraries yet.
++  if (getTriple().getOS() != llvm::Triple::Solaris) {
+   if (!isInSanitizerBlacklist(Fn, Loc)) {
+     if (getLangOpts().Sanitize.hasOneOf(SanitizerKind::Address |
+                                         SanitizerKind::KernelAddress))
+@@ -278,6 +298,7 @@
+     if (getLangOpts().Sanitize.has(SanitizerKind::SafeStack))
+       Fn->addFnAttr(llvm::Attribute::SafeStack);
+   }
++  }
+ 
+   return Fn;
+ }
+@@ -289,9 +310,19 @@
+                                           llvm::GlobalVariable *GV,
+                                           llvm::Function *InitFunc,
+                                           InitSegAttr *ISA) {
+-  llvm::GlobalVariable *PtrArray = new llvm::GlobalVariable(
+-      TheModule, InitFunc->getType(), /*isConstant=*/true,
+-      llvm::GlobalValue::PrivateLinkage, InitFunc, "__cxx_init_fn_ptr");
++  std::string GVN("__cxx_init_fn_ptr");
++  if (getTriple().getOS() == llvm::Triple::Solaris) {
++    GVN += "_";
++    GVN += std::to_string(InitPriority);
++  }
++
++  llvm::GlobalVariable *PtrArray =
++    new llvm::GlobalVariable(TheModule, InitFunc->getType(),
++                             /*isConstant=*/ true,
++                             llvm::GlobalValue::PrivateLinkage,
++                             InitFunc, GVN);
++  assert(PtrArray && "Invalid Function Pointer Array!");
++
+   PtrArray->setSection(ISA->getSection());
+   addUsedGlobal(PtrArray);
+ 
+@@ -309,10 +340,23 @@
+   if (I != DelayedCXXInitPosition.end() && I->second == ~0U)
+     return;
+ 
+-  llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
+-  SmallString<256> FnName;
++  llvm::FunctionType *FTy = nullptr;
++  std::vector<llvm::Type*> ArgsVec;
++
++  if (getTriple().getOS() == llvm::Triple::Solaris) {
++    ArgsVec.push_back(IntTy);
++    ArgsVec.push_back(IntTy);
++    FTy = llvm::FunctionType::get(VoidTy, ArgsVec, false);
++  } else {
++    FTy = llvm::FunctionType::get(VoidTy, false);
++  }
++
++  SmallString<512> FnName;
+   {
+     llvm::raw_svector_ostream Out(FnName);
++    if (getTriple().getOS() == llvm::Triple::Solaris)
++      getCXXABI().getMangleContext().mangleGCCDynamicInitializer(D, Out);
++    else
+     getCXXABI().getMangleContext().mangleDynamicInitializer(D, Out);
+   }
+ 
+@@ -321,12 +365,55 @@
+       CreateGlobalInitOrDestructFunction(FTy, FnName.str(),
+                                          getTypes().arrangeNullaryFunction(),
+                                          D->getLocation());
++  Fn->setDoesNotThrow();
+ 
+   auto *ISA = D->getAttr<InitSegAttr>();
+-  CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr,
+-                                                          PerformInit);
++  if (getTriple().getOS() == llvm::Triple::Solaris) {
++    ASTContext &Ctx = getContext();
++    VarDecl *DD = const_cast<VarDecl*>(D);
++
++    assert(D && "const VarDecl is NULL?!");
++    assert(DD && "VarDecl is NULL?!");
++
++    auto *IPA = D->getAttr<InitPriorityAttr>();
++    if (!IPA) {
++      IPA = InitPriorityAttr::CreateImplicit(Ctx, /* InitPriority */ 65535);
++      DD->addAttr(IPA);
++    }
+ 
+-  llvm::GlobalVariable *COMDATKey =
++    if (!ISA && CodeGenOpts.UseInitArray) {
++      ISA = InitSegAttr::CreateImplicit(Ctx, PerformInit ?
++                                        StringRef(".init_array") :
++                                        StringRef(".fini_array"));
++      DD->addAttr(ISA);
++    }
++  }
++
++  FunctionArgList ArgList;
++  ASTContext &Ctx = getContext();
++  // We cannot allocate these dynamically because of an ill-conceived
++  // operator new overload in DeclBase.h.
++  ImplicitParamDecl IAFirst(Ctx, /*DC=*/ nullptr, D->getLocation(),
++                            /*Id=*/ nullptr, Ctx.UnsignedIntTy);
++  ImplicitParamDecl IASecond(Ctx, /*DC=*/ nullptr, D->getLocation(),
++                             /*Id=*/ nullptr, Ctx.UnsignedIntTy);
++
++  if (getTriple().getOS() == llvm::Triple::Solaris) {
++    // Add Parameters to the Function ArgumentList on Solaris
++    // for compatibility with the GCC C++ Runtime.
++    ArgList.push_back(&IAFirst);
++    ArgList.push_back(&IASecond);
++  }
++
++  CodeGenFunction CGF(*this);
++  CGF.GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr, PerformInit, ArgList);
++
++  llvm::GlobalVariable *COMDATKey;
++
++  if (getTriple().getOS() == llvm::Triple::Solaris)
++    COMDATKey = D->isExternallyVisible() ? Addr : nullptr;
++  else
++    COMDATKey =
+       supportsCOMDAT() && D->isExternallyVisible() ? Addr : nullptr;
+ 
+   if (D->getTLSKind()) {
+@@ -412,25 +499,35 @@
+         PrioE = std::upper_bound(I + 1, E, *I, GlobalInitPriorityCmp());
+ 
+       LocalCXXGlobalInits.clear();
+-      unsigned Priority = I->first.priority;
++
++      // Priority is always <= 65535 (enforced by sema).
++      unsigned Priority =
++        I->first.priority > 65535U ? 65535U : I->first.priority;
++
+       // Compute the function suffix from priority. Prepend with zeroes to make
+       // sure the function names are also ordered as priorities.
+-      std::string PrioritySuffix = llvm::utostr(Priority);
+-      // Priority is always <= 65535 (enforced by sema).
+-      PrioritySuffix = std::string(6-PrioritySuffix.size(), '0')+PrioritySuffix;
+-      llvm::Function *Fn = CreateGlobalInitOrDestructFunction(
+-          FTy, "_GLOBAL__I_" + PrioritySuffix, FI);
++      std::string PrioritySuffix = "0";
++      PrioritySuffix += std::to_string(Priority);
++      std::string FunctionName = "_GLOBAL__I_";
++      FunctionName += PrioritySuffix;
++      llvm::Twine FNm(FunctionName);
++      llvm::Function *Fn = CreateGlobalInitOrDestructFunction(FTy, FNm, FI);
+ 
+       for (; I < PrioE; ++I)
+         LocalCXXGlobalInits.push_back(I->second);
+ 
+-      CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, LocalCXXGlobalInits);
++      CodeGenFunction CGF(*this);
++      CGF.GenerateCXXGlobalInitFunc(Fn, LocalCXXGlobalInits);
+       AddGlobalCtor(Fn, Priority);
+     }
++
+     PrioritizedCXXGlobalInits.clear();
+   }
+ 
+-  SmallString<128> FileName;
++  if (CXXGlobalInits.empty())
++    return;
++
++  SmallString<PATH_MAX> FileName;
+   SourceManager &SM = Context.getSourceManager();
+   if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
+     // Include the filename in the symbol name. Including "sub_" matches gcc and
+@@ -444,14 +541,15 @@
+   for (size_t i = 0; i < FileName.size(); ++i) {
+     // Replace everything that's not [a-zA-Z0-9._] with a _. This set happens
+     // to be the set of C preprocessing numbers.
+-    if (!isPreprocessingNumberBody(FileName[i]))
++    if (!isPreprocessingNumberBody(FileName[i]) || (FileName[i] == '.'))
+       FileName[i] = '_';
+   }
+ 
+-  llvm::Function *Fn = CreateGlobalInitOrDestructFunction(
+-      FTy, llvm::Twine("_GLOBAL__sub_I_", FileName), FI);
++  llvm::Twine FNm("_GLOBAL__sub_I_", FileName);
++  llvm::Function *Fn = CreateGlobalInitOrDestructFunction(FTy, FNm, FI);
+ 
+-  CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, CXXGlobalInits);
++  CodeGenFunction CGF(*this);
++  CGF.GenerateCXXGlobalInitFunc(Fn, CXXGlobalInits);
+   AddGlobalCtor(Fn);
+ 
+   CXXGlobalInits.clear();
+@@ -473,29 +571,47 @@
+ }
+ 
+ /// Emit the code necessary to initialize the given global variable.
+-void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
++void
++CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
+                                                        const VarDecl *D,
+                                                  llvm::GlobalVariable *Addr,
+-                                                       bool PerformInit) {
++                                                  bool PerformInit,
++                                                  const FunctionArgList &ArgList) {
+   // Check if we need to emit debug info for variable initializer.
+   if (D->hasAttr<NoDebugAttr>())
+     DebugInfo = nullptr; // disable debug info indefinitely for this function
+ 
+   CurEHLocation = D->getLocStart();
++  ASTContext &Ctx = getContext();
++
++  FunctionType::ExtInfo ExtInfo;
++  const CGFunctionInfo &FuncInfo =
++    getTypes().arrangeFreeFunctionDeclaration(Ctx.VoidTy, ArgList,
++                                              ExtInfo, /*IsVariadic=*/ false);
++  GlobalDecl GD(D);
+ 
+-  StartFunction(GlobalDecl(D), getContext().VoidTy, Fn,
+-                getTypes().arrangeNullaryFunction(),
+-                FunctionArgList(), D->getLocation(),
++  StartFunction(GD, Ctx.VoidTy, Fn, FuncInfo, ArgList, D->getLocation(),
+                 D->getInit()->getExprLoc());
+ 
+   // Use guarded initialization if the global variable is weak. This
+   // occurs for, e.g., instantiated static data members and
+   // definitions explicitly marked weak.
++  if (CGM.getTriple().getOS() == llvm::Triple::Solaris) {
++    if (Addr->hasWeakLinkage() || Addr->hasLinkOnceLinkage()) {
++      EmitCXXGuardedInit(*D, Addr, PerformInit);
++    } else {
++      EmitCXXGlobalVarDeclInit(*D, Addr, PerformInit);
++    }
++  } else {
++    // Use guarded initialization if the global variable is weak. This
++    // occurs for, e.g., instantiated static data members and
++    // definitions explicitly marked weak.
+   if (Addr->hasWeakLinkage() || Addr->hasLinkOnceLinkage()) {
+     EmitCXXGuardedInit(*D, Addr, PerformInit);
+   } else {
+     EmitCXXGlobalVarDeclInit(*D, Addr, PerformInit);
+   }
++  }
+ 
+   FinishFunction();
+ }
+@@ -504,10 +620,21 @@
+ CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
+                                            ArrayRef<llvm::Function *> Decls,
+                                            Address Guard) {
+-  {
++  llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
++  ASTContext &Ctx = getContext();
++  llvm::LLVMContext &LLVMCtx = CGM.getLLVMContext();
++
++  { // Why?
+     auto NL = ApplyDebugLocation::CreateEmpty(*this);
+-    StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
+-                  getTypes().arrangeNullaryFunction(), FunctionArgList());
++
++    FunctionArgList ArgList;
++    FunctionType::ExtInfo ExtInfo;
++    const CGFunctionInfo &FuncInfo =
++      getTypes().arrangeFreeFunctionDeclaration(Ctx.VoidTy, ArgList,
++                                                ExtInfo,
++                                                /*IsVariadic=*/ false);
++    StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, FuncInfo, ArgList);
++
+     // Emit an artificial location for this function.
+     auto AL = ApplyDebugLocation::CreateArtificial(*this);
+ 
+@@ -525,7 +652,8 @@
+       // Mark as initialized before initializing anything else. If the
+       // initializers use previously-initialized thread_local vars, that's
+       // probably supposed to be OK, but the standard doesn't say.
+-      Builder.CreateStore(llvm::ConstantInt::get(GuardVal->getType(),1), Guard);
++      Builder.CreateStore(llvm::ConstantInt::get(GuardVal->getType(), 1),
++                          Guard);
+     }
+ 
+     RunCleanupsScope Scope(*this);
+@@ -537,9 +665,27 @@
+       EmitObjCAutoreleasePoolCleanup(token);
+     }
+ 
+-    for (unsigned i = 0, e = Decls.size(); i != e; ++i)
+-      if (Decls[i])
+-        EmitRuntimeCall(Decls[i]);
++    for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
++      if (llvm::Function *FV = Decls[i]) {
++        if (CGM.getTriple().getOS() == llvm::Triple::Solaris) {
++          llvm::Value *Values[2] = { nullptr, nullptr };
++          Values[0] =
++            llvm::ConstantInt::get(llvm::Type::getInt32Ty(LLVMCtx), 1);
++          Values[1] =
++            llvm::ConstantInt::get(llvm::Type::getInt32Ty(LLVMCtx), 65535);
++          ArrayRef<llvm::Value*> ArgValues = llvm::makeArrayRef(Values);
++          llvm::CallInst *CI = EmitRuntimeCall(FV, ArgValues);
++#ifndef NDEBUG
++          llvm::Function *CIF = CI->getCalledFunction();
++          assert (CIF && "Invalid function returned in CallInst!");
++#else
++          (void) CI;
++#endif
++        } else {
++          EmitRuntimeCall(FV);
++        }
++      }
++    }
+ 
+     Scope.ForceCleanup();
+ 
+@@ -547,7 +693,7 @@
+       Builder.CreateBr(ExitBlock);
+       EmitBlock(ExitBlock);
+     }
+-  }
++  } // Why?
+ 
+   FinishFunction();
+ }
+###
+--- tools/clang/lib/CodeGen/CGExprCXX.cpp	2015-11-22 22:01:14.000000000 -0500
++++ tools/clang/lib/CodeGen/CGExprCXX.cpp	2016-05-08 23:19:20.566431579 -0400
+@@ -1203,6 +1203,10 @@
+       EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
+     }
+   };
++  static_assert(
++      llvm::AlignOf<CallDeleteDuringNew>::Alignment >=
++          llvm::AlignOf<RValue>::Alignment,
++      "Alignment is insufficient for objects appended to CallDeleteDuringNew");
+ 
+   /// A cleanup to call the given 'operator delete' function upon
+   /// abnormal exit from a new expression when the new expression is
+@@ -1262,6 +1266,10 @@
+       EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
+     }
+   };
++  static_assert(
++      llvm::AlignOf<CallDeleteDuringConditionalNew>::Alignment >=
++          llvm::AlignOf<DominatingValue<RValue>::saved_type>::Alignment,
++      "Alignment is insufficient for objects appended to CallDeleteDuringNew");
+ }
+ 
+ /// Enter a cleanup to call 'operator delete' if the initializer in a
+###
+--- tools/clang/lib/CodeGen/CodeGenFunction.h	2016-01-21 20:07:48.000000000 -0800
++++ tools/clang/lib/CodeGen/CodeGenFunction.h	2016-05-11 10:04:52.119577478 -0700
+@@ -2925,7 +2925,9 @@
+   void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
+                                         const VarDecl *D,
+                                         llvm::GlobalVariable *Addr,
+-                                        bool PerformInit);
++                                        bool PerformInit,
++                                        const FunctionArgList &ArgList =
++                                        FunctionArgList());
+ 
+   void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest);
+   
+###
+--- tools/clang/lib/CodeGen/CodeGenModule.cpp	2016-01-08 15:48:26.000000000 -0500
++++ tools/clang/lib/CodeGen/CodeGenModule.cpp	2016-05-08 23:19:20.567431604 -0400
+@@ -293,8 +293,16 @@
+       Error = true;
+       Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
+     } else if (GV->isDeclaration()) {
+-      Error = true;
+-      Diags.Report(AA->getLocation(), diag::err_alias_to_undefined);
++      clang::Linkage L = D->getFormalLinkage();
++      const auto *FD = cast<FunctionDecl>(D);
++
++      if (!FD && ((L != clang::ExternalLinkage) &&
++                  (L != clang::UniqueExternalLinkage) &&
++                  (L != clang::InternalLinkage) &&
++                  (L != clang::VisibleNoLinkage))) {
++        Error = true;
++        Diags.Report(AA->getLocation(), diag::err_alias_to_undefined);
++      }
+     }
+ 
+     llvm::Constant *Aliasee = Alias->getAliasee();
+@@ -326,6 +334,7 @@
+       }
+     }
+   }
++
+   if (!Error)
+     return;
+ 
+@@ -1481,10 +1490,7 @@
+ 
+ void CodeGenModule::EmitGlobal(GlobalDecl GD) {
+   const auto *Global = cast<ValueDecl>(GD.getDecl());
+-
+-  // Weak references don't produce any output by themselves.
+-  if (Global->hasAttr<WeakRefAttr>())
+-    return;
++  assert(Global && "Cast to ValueDecl yields nullptr!");
+ 
+   // If this is an alias definition (which otherwise looks like a declaration)
+   // emit it now.
+@@ -1699,16 +1705,11 @@
+ void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
+   const auto *D = cast<ValueDecl>(GD.getDecl());
+ 
+-  PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 
++  PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
+                                  Context.getSourceManager(),
+                                  "Generating code for declaration");
+-  
+-  if (isa<FunctionDecl>(D)) {
+-    // At -O0, don't generate IR for functions with available_externally 
+-    // linkage.
+-    if (!shouldEmitFunction(GD))
+-      return;
+ 
++  if (isa<FunctionDecl>(D)) {
+     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
+       CompleteDIClassType(Method);
+       // Make sure to emit the definition(s) before we emit the thunks.
+@@ -1726,13 +1727,17 @@
+       return;
+     }
+ 
+-    return EmitGlobalFunctionDefinition(GD, GV);
++    EmitGlobalFunctionDefinition(GD, GV);
++    return;
++  }
++
++  if (const auto *VD = dyn_cast<VarDecl>(D)) {
++    EmitGlobalVarDefinition(VD);
++    return;
+   }
+ 
+-  if (const auto *VD = dyn_cast<VarDecl>(D))
+-    return EmitGlobalVarDefinition(VD);
+-  
+-  llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
++  llvm::errs() << __PRETTY_FUNCTION__
++    << ": Invalid argument to EmitGlobalDefinition()!\n";
+ }
+ 
+ static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
+--- tools/clang/lib/CodeGen/CodeGenModule.h	2016-01-06 09:35:46.000000000 -0500
++++ tools/clang/lib/CodeGen/CodeGenModule.h	2016-05-08 23:19:20.568431628 -0400
+@@ -684,7 +684,8 @@
+                                     llvm::GlobalValue::LinkageTypes Linkage);
+ 
+   llvm::Function *
+-  CreateGlobalInitOrDestructFunction(llvm::FunctionType *ty, const Twine &name,
++  CreateGlobalInitOrDestructFunction(llvm::FunctionType *FTy,
++                                     const Twine &Name,
+                                      const CGFunctionInfo &FI,
+                                      SourceLocation Loc = SourceLocation(),
+                                      bool TLS = false);
+--- tools/clang/lib/CodeGen/EHScopeStack.h	2015-12-12 00:39:21.000000000 -0500
++++ tools/clang/lib/CodeGen/EHScopeStack.h	2016-05-08 23:19:20.568431628 -0400
+@@ -267,7 +267,8 @@
+   ~EHScopeStack() { delete[] StartOfBuffer; }
+ 
+   /// Push a lazily-created cleanup on the stack.
+-  template <class T, class... As> void pushCleanup(CleanupKind Kind, As... A) {
++  template <class T, class... As>
++  void pushCleanup(CleanupKind Kind, As... A) {
+     static_assert(llvm::AlignOf<T>::Alignment <= ScopeStackAlignment,
+                   "Cleanup's alignment is too large.");
+     void *Buffer = pushCleanup(Kind, sizeof(T));
+###
+
--- a/components/llvm/patches/012-TypeLocBuilder.cpp.patch	Thu Jul 28 16:15:45 2016 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,73 +0,0 @@
-# https://llvm.org/bugs/show_bug.cgi?id=24615
---- tools/clang/lib/Sema/TypeLocBuilder.h	2014-08-13 09:25:19.000000000 -0700
-+++ tools/clang/lib/Sema/TypeLocBuilder.h	2015-08-28 16:45:41.733661825 -0700
-@@ -39,7 +39,7 @@
- #endif
-     
-   /// The inline buffer.
--  enum { BufferMaxAlignment = llvm::AlignOf<void*>::Alignment };
-+  enum { BufferMaxAlignment = llvm::AlignOf<uint64_t>::Alignment };
-   llvm::AlignedCharArray<BufferMaxAlignment, InlineCapacity> InlineBuffer;
-   unsigned NumBytesAtAlign4, NumBytesAtAlign8;
- 
-@@ -52,7 +52,7 @@
- 
-   ~TypeLocBuilder() {
-     if (Buffer != InlineBuffer.buffer)
--      delete[] Buffer;
-+      std::free(Buffer);
-   }
- 
-   /// Ensures that this buffer has at least as much capacity as described.
---- tools/clang/lib/Sema/TypeLocBuilder.cpp	2014-05-25 23:22:03.000000000 -0700
-+++ tools/clang/lib/Sema/TypeLocBuilder.cpp	2015-08-25 18:53:43.000000000 -0700
-@@ -13,6 +13,8 @@
- //===----------------------------------------------------------------------===//
- 
- #include "TypeLocBuilder.h"
-+#include <cstring>
-+#include <stdlib.h>
- 
- using namespace clang;
- 
-@@ -46,14 +48,36 @@
-   assert(NewCapacity > Capacity);
- 
-   // Allocate the new buffer and copy the old data into it.
--  char *NewBuffer = new char[NewCapacity];
-+  char *NewBuffer;
-+
-+#if defined(_MSC_VER)
-+  NewBuffer = _aligned_malloc(NewCapacity, (size_t) BufferMaxAlignment);
-+  assert(NewBuffer && "_aligned_malloc failed!");
-+  if (!NewBuffer) {
-+    llvm::errs() << __PRETTY_FUNCTION__ << ": _aligned_malloc failed!\n";
-+    abort();
-+  }
-+#else
-+  int R = posix_memalign((void**) &NewBuffer,
-+                         (size_t) BufferMaxAlignment, NewCapacity);
-+  assert((R == 0) && "posix_memalign failed!");
-+  assert(NewBuffer && "posix_memalign failed!");
-+  if ((R != 0) || (!NewBuffer)) {
-+    llvm::errs() << __PRETTY_FUNCTION__ << ": posix_memalign failed!\n";
-+    abort();
-+  }
-+#endif
-+
-+  (void) std::memset(NewBuffer, 0, NewCapacity);
-+
-   unsigned NewIndex = Index + NewCapacity - Capacity;
--  memcpy(&NewBuffer[NewIndex],
-+  (void) std::memcpy(&NewBuffer[NewIndex],
-          &Buffer[Index],
-          Capacity - Index);
- 
--  if (Buffer != InlineBuffer.buffer)
--    delete[] Buffer;
-+  if (Buffer != InlineBuffer.buffer) {
-+    std::free(Buffer);
-+  }
- 
-   Buffer = NewBuffer;
-   Capacity = NewCapacity;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/012-solaris-clang-libclangDriver.patch	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,2506 @@
+# 23701635 clang produces amd64 opcodes, but calls 32-bit assembler by default
+# 23854357 clang should check for GNU ld
+# 22778650 clang should support OpenMP because it can
+# 24314745 clang should support PIE executables in Solaris
+# 3.9.X for upstream.
+--- tools/clang/include/clang/Driver/Options.td	2016-01-06 16:27:42.000000000 -0500
++++ tools/clang/include/clang/Driver/Options.td	2016-05-08 23:19:20.553431263 -0400
+@@ -669,6 +669,9 @@
+   Flags<[CC1Option]>, HelpText<"Form fused FP ops (e.g. FMAs): fast (everywhere)"
+   " | on (according to FP_CONTRACT pragma, default) | off (never fuse)">;
+ 
++def fabi_version_EQ : Joined<["-"], "fabi-version=">, Group<f_Group>,
++  Flags<[CC1Option]>, HelpText<"Use specified GNU C++ ABI version">;
++
+ def ffor_scope : Flag<["-"], "ffor-scope">, Group<f_Group>;
+ def fno_for_scope : Flag<["-"], "fno-for-scope">, Group<f_Group>;
+ 
+@@ -1312,6 +1315,12 @@
+ def meabi : Separate<["-"], "meabi">, Group<m_Group>, Flags<[CC1Option]>,
+   HelpText<"Set EABI type, e.g. 4, 5 or gnu (default depends on triple)">;
+ 
++// SPARC-only options.
++def mvis : Flag<["-"], "mvis">, Group<m_Group>;
++def mvis2 : Flag<["-"], "mvis2">, Group<m_Group>;
++def mvis3 : Flag<["-"], "mvis3">, Group<m_Group>;
++def mimpure_text: Flag<["-"], "mimpure-text">, Group<m_Group>;
++
+ def mmmx : Flag<["-"], "mmmx">, Group<m_x86_Features_Group>;
+ def mno_3dnowa : Flag<["-"], "mno-3dnowa">, Group<m_x86_Features_Group>;
+ def mno_3dnow : Flag<["-"], "mno-3dnow">, Group<m_x86_Features_Group>;
+@@ -1954,6 +1963,7 @@
+ 
+ def fprofile_dir : Joined<["-"], "fprofile-dir=">, Group<clang_ignored_gcc_optimization_f_Group>;
+ 
++def fuse_as_EQ : Joined<["-"], "fuse-as=">, Group<f_Group>;
+ def fuse_ld_EQ : Joined<["-"], "fuse-ld=">, Group<f_Group>;
+ 
+ defm align_functions : BooleanFFlag<"align-functions">, Group<clang_ignored_gcc_optimization_f_Group>;
+###
+--- tools/clang/lib/Driver/Multilib.cpp	2015-10-12 10:32:57.000000000 -0400
++++ tools/clang/lib/Driver/Multilib.cpp	2016-05-08 23:19:20.569431652 -0400
+@@ -171,11 +171,11 @@
+ }
+ 
+ static Multilib compose(const Multilib &Base, const Multilib &New) {
+-  SmallString<128> GCCSuffix;
++  SmallString<PATH_MAX> GCCSuffix;
+   llvm::sys::path::append(GCCSuffix, "/", Base.gccSuffix(), New.gccSuffix());
+-  SmallString<128> OSSuffix;
++  SmallString<PATH_MAX> OSSuffix;
+   llvm::sys::path::append(OSSuffix, "/", Base.osSuffix(), New.osSuffix());
+-  SmallString<128> IncludeSuffix;
++  SmallString<PATH_MAX> IncludeSuffix;
+   llvm::sys::path::append(IncludeSuffix, "/", Base.includeSuffix(),
+                           New.includeSuffix());
+ 
+###
+--- tools/clang/lib/Driver/ToolChains.cpp	2016-02-16 10:56:48.000000000 -0900
++++ tools/clang/lib/Driver/ToolChains.cpp	2016-06-30 09:27:01.031173505 -0800
+@@ -28,12 +28,15 @@
+ #include "llvm/ProfileData/InstrProf.h"
+ #include "llvm/Support/ErrorHandling.h"
+ #include "llvm/Support/FileSystem.h"
++#include "llvm/Support/Host.h"
+ #include "llvm/Support/MemoryBuffer.h"
+ #include "llvm/Support/Path.h"
+ #include "llvm/Support/Program.h"
+ #include "llvm/Support/TargetParser.h"
+ #include "llvm/Support/raw_ostream.h"
+ #include <cstdlib> // ::getenv
++#include <cstring>
++#include <cctype>
+ #include <system_error>
+ 
+ using namespace clang::driver;
+@@ -41,6 +44,15 @@
+ using namespace clang;
+ using namespace llvm::opt;
+ 
++#if defined(LLVM_ON_UNIX)
++#include <cstring>
++#include <cctype>
++#include <sys/types.h>
++#include <sys/stat.h>
++#include <dirent.h>
++#include <unistd.h>
++#endif
++
+ MachO::MachO(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
+     : ToolChain(D, Triple, Args) {
+   // We expect 'as', 'ld', etc. to be adjacent to our install dir.
+@@ -1347,6 +1359,11 @@
+     // If we have a SysRoot, try that first.
+     if (!D.SysRoot.empty()) {
+       Prefixes.push_back(D.SysRoot);
++
++      // Add Solaris-specific GCC locations.
++      if (TargetTriple.getOS() == llvm::Triple::Solaris)
++        Prefixes.push_back("/usr/gcc");
++
+       Prefixes.push_back(D.SysRoot + "/usr");
+     }
+ 
+@@ -1434,14 +1451,17 @@
+   static const char *const ARMebHFTriples[] = {
+       "armeb-linux-gnueabihf", "armebv7hl-redhat-linux-gnueabi"};
+ 
+-  static const char *const X86_64LibDirs[] = {"/lib64", "/lib"};
++  static const char *const X86_64LibDirs[] = {"/lib64", "/lib/amd64",
++                                               "/lib/64", "/lib"};
+   static const char *const X86_64Triples[] = {
+       "x86_64-linux-gnu",       "x86_64-unknown-linux-gnu",
+       "x86_64-pc-linux-gnu",    "x86_64-redhat-linux6E",
+       "x86_64-redhat-linux",    "x86_64-suse-linux",
+       "x86_64-manbo-linux-gnu", "x86_64-linux-gnu",
+       "x86_64-slackware-linux", "x86_64-linux-android",
+-      "x86_64-unknown-linux"};
++      "x86_64-unknown-linux", "x86_64-pc-solaris2.11",
++      "x86_64-pc-solaris2.12", "x86_64-pc-solaris2.13" };
++
+   static const char *const X32LibDirs[] = {"/libx32"};
+   static const char *const X86LibDirs[] = {"/lib32", "/lib"};
+   static const char *const X86Triples[] = {
+@@ -1449,7 +1469,8 @@
+       "i386-linux-gnu",       "i386-redhat-linux6E",   "i686-redhat-linux",
+       "i586-redhat-linux",    "i386-redhat-linux",     "i586-suse-linux",
+       "i486-slackware-linux", "i686-montavista-linux", "i686-linux-android",
+-      "i586-linux-gnu"};
++      "i586-linux-gnu", "i386-pc-solaris2.11", "i386-pc-solaris2.12",
++      "i386-pc-solaris2.13" };
+ 
+   static const char *const MIPSLibDirs[] = {"/lib"};
+   static const char *const MIPSTriples[] = {"mips-linux-gnu", "mips-mti-linux",
+@@ -1483,30 +1504,28 @@
+ 
+   static const char *const SPARCv8LibDirs[] = {"/lib32", "/lib"};
+   static const char *const SPARCv8Triples[] = {"sparc-linux-gnu",
+-                                               "sparcv8-linux-gnu"};
+-  static const char *const SPARCv9LibDirs[] = {"/lib64", "/lib"};
++                                               "sparcv8-linux-gnu",
++                                               "sparc-sun-solaris2.11",
++                                               "sparc-sun-solaris2.12",
++                                               "sparc-sun-solaris2.13" };
++
++  static const char *const SPARCv9LibDirs[] = {"/lib64", "/lib/sparcv9",
++                                                "/lib/64", "/lib" };
++
+   static const char *const SPARCv9Triples[] = {"sparc64-linux-gnu",
+-                                               "sparcv9-linux-gnu"};
++                                               "sparcv9-linux-gnu",
++                                               "sparcv9-sun-solaris2.11",
++                                               "sparcv9-sun-solaris2.12",
++                                               "sparcv9-sun-solaris2.13"  };
+ 
+   static const char *const SystemZLibDirs[] = {"/lib64", "/lib"};
+   static const char *const SystemZTriples[] = {
+       "s390x-linux-gnu", "s390x-unknown-linux-gnu", "s390x-ibm-linux-gnu",
+       "s390x-suse-linux", "s390x-redhat-linux"};
+ 
+-  // Solaris.
+-  static const char *const SolarisSPARCLibDirs[] = {"/gcc"};
+-  static const char *const SolarisSPARCTriples[] = {"sparc-sun-solaris2.11",
+-                                                    "i386-pc-solaris2.11"};
+-
+   using std::begin;
+   using std::end;
+ 
+-  if (TargetTriple.getOS() == llvm::Triple::Solaris) {
+-    LibDirs.append(begin(SolarisSPARCLibDirs), end(SolarisSPARCLibDirs));
+-    TripleAliases.append(begin(SolarisSPARCTriples), end(SolarisSPARCTriples));
+-    return;
+-  }
+-
+   switch (TargetTriple.getArch()) {
+   case llvm::Triple::aarch64:
+     LibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
+@@ -3302,69 +3321,783 @@
+ }
+ 
+ /// Solaris - Solaris tool chain which can call as(1) and ld(1) directly.
++bool Solaris::SupportsClangLibCPlusPlus = false;
+ 
+ Solaris::Solaris(const Driver &D, const llvm::Triple &Triple,
+-                 const ArgList &Args)
+-    : Generic_GCC(D, Triple, Args) {
++                 const llvm::opt::ArgList &Args)
++  : Generic_ELF(D, Triple, Args),
++  UseGnuAs(true),
++  UseGnuLd(false),
++  UseGoldLd(false),
++  UseSunLd(true),
++  UseMediatedGCCToolChainPath(false),
++  UseSpecifiedGCCToolChainPath(false),
++  IsValid(false),
++  GCCInstallDir("/usr/gcc/"),
++  GCCMajorMinor(""),
++  GCCMajorMinorMicro(""),
++  GCCInternalLibDir(""),
++  GCCInternalMultiLibDir(""),
++  GCCIncludeDirs(),
++  Assembler("/usr/gnu/bin/as"),
++  Linker("/usr/bin/ld"),
++  mtune(""),
++  march(""),
++  mcpu(""),
++  ExtraOpts() {
++    if (Arg *A = Args.getLastArg(options::OPT_gcc_toolchain)) {
++      GCCInstallDir = A->getValue();
++      if (!llvm::sys::fs::exists(GCCInstallDir))
++        D.Diag(diag::err_drv_no_such_file) << GCCInstallDir;
++      else {
++        findSpecifiedGCCToolchain(GCCInstallDir.c_str(), Triple, Args);
++
++        if (!UseSpecifiedGCCToolChainPath) {
++          D.Diag(diag::err_drv_unsupported_rtlib_for_platform)
++            << GCCInstallDir << Triple.getTriple();
++        } else {
++          findGCCIncludeDirs(Triple, Args);
++          findGCCInternalLibDir(Triple, Args);
++        }
++      }
++    } else {
++      findGCCMajorMinor();
++      findGCCMajorMinorMicro(Triple);
++      findGCCIncludeDirs(Triple, Args);
++      findGCCInternalLibDir(Triple, Args);
++    }
+ 
+-  GCCInstallation.init(Triple, Args);
++    if (Arg *A = Args.getLastArg(options::OPT_fuse_ld_EQ)) {
++      Linker = A->getValue();
++      if (Linker == "bfd")
++        Linker = "/usr/gnu/bin/ld";
++      else if (Linker == "gold")
++        Linker = "/usr/gnu/bin/ld.gold";
++
++      if ((Linker == "/usr/gnu/bin/ld") || (Linker == "/usr/gnu/bin/ld.bfd") ||
++          (Linker == "/usr/bin/gld") || (Linker == "/usr/bin/gld.bfd")) {
++        UseGnuLd = true;
++        UseGoldLd = false;
++        UseSunLd = false;
++      } else if ((Linker == "/usr/gnu/bin/ld.gold") ||
++                 (Linker == "/usr/bin/gld.gold") ||
++                 (Linker == "/usr/bin/ld.gold")) {
++        UseGnuLd = false;
++        UseSunLd = false;
++        UseGoldLd = true;
++      }
++    }
+ 
+-  path_list &Paths = getFilePaths();
+-  if (GCCInstallation.isValid())
+-    addPathIfExists(D, GCCInstallation.getInstallPath(), Paths);
++    if (Arg *A = Args.getLastArg(options::OPT_fuse_as_EQ)) {
++      Assembler = A->getValue();
++      if (Assembler == "llvm")
++        UseGnuAs = false;
++      else if ((Assembler == "/usr/gnu/bin/as") ||
++               (Assembler == "/usr/bin/gas"))
++        UseGnuAs = true;
++      else if (Assembler == "gas") {
++        Assembler = "/usr/gnu/bin/as";
++        UseGnuAs = true;
++      } else if ((Assembler == "/usr/bin/as") || (Assembler == "sun") ||
++                 (Assembler == "solaris"))
++        D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
++    }
++
++    getProgramPaths().push_back(GCCInstallDir);
+ 
+-  addPathIfExists(D, getDriver().getInstalledDir(), Paths);
+   if (getDriver().getInstalledDir() != getDriver().Dir)
+-    addPathIfExists(D, getDriver().Dir, Paths);
++      getProgramPaths().push_back(getDriver().Dir);
+ 
+-  addPathIfExists(D, getDriver().SysRoot + getDriver().Dir + "/../lib", Paths);
++    llvm::Triple::ArchType Arch = Triple.getArch();
+ 
+-  std::string LibPath = "/usr/lib/";
+-  switch (Triple.getArch()) {
++    switch (Arch) {
+   case llvm::Triple::x86:
++      getFilePaths().push_back(getDriver().Dir + "/../lib");
++      getFilePaths().push_back("/usr/lib");
++      march = mtune = "i686";
++      break;
+   case llvm::Triple::sparc:
++      getFilePaths().push_back(getDriver().Dir + "/../lib");
++      getFilePaths().push_back("/usr/lib");
++      mcpu = "ultrasparc";
++      mtune = "ultrasparc";
++      march = "v8plusa";
+     break;
+   case llvm::Triple::x86_64:
+-    LibPath += "amd64/";
++      getFilePaths().push_back(getDriver().Dir + "/../lib/amd64");
++      getFilePaths().push_back("/usr/lib/amd64");
++      march = mtune = "opteron";
+     break;
+   case llvm::Triple::sparcv9:
+-    LibPath += "sparcv9/";
++      getFilePaths().push_back(getDriver().Dir + "/../lib/sparcv9");
++      getFilePaths().push_back("/usr/lib/sparcv9");
++      mcpu = "ultrasparc";
++      mtune = "ultrasparc";
++      march = "v9a";
+     break;
+   default:
+-    llvm_unreachable("Unsupported architecture");
++      getFilePaths().push_back(getDriver().Dir + "/../lib");
++      getFilePaths().push_back("/usr/lib");
++      break;
+   }
+ 
+-  addPathIfExists(D, getDriver().SysRoot + LibPath, Paths);
++    validate();
++
++    if (Args.hasArg(options::OPT_v))
++      this->print(llvm::errs());
+ }
+ 
+-Tool *Solaris::buildAssembler() const {
+-  return new tools::solaris::Assembler(*this);
++std::string Solaris::computeSysRoot() const {
++  if (!getDriver().SysRoot.empty())
++    return getDriver().SysRoot;
++
++  return std::string("/");
+ }
+ 
+-Tool *Solaris::buildLinker() const { return new tools::solaris::Linker(*this); }
++bool
++Solaris::addLibStdCXXIncludePaths(Twine Base, Twine Suffix,
++                                  StringRef GCCTriple,
++                                  StringRef GCCMultiarchTriple,
++                                  StringRef TargetMultiarchTriple,
++                                  Twine IncludeSuffix,
++                                  const llvm::opt::ArgList &DriverArgs,
++                                  llvm::opt::ArgStringList &CC1Args) const {
++  if (!llvm::sys::fs::exists(Base + Suffix))
++    return false;
+ 
+-void Solaris::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
+-                                           ArgStringList &CC1Args) const {
++  addSystemInclude(DriverArgs, CC1Args, Base);
++  addSystemInclude(DriverArgs, CC1Args, Base + Suffix);
++
++  if ((GCCMultiarchTriple.empty() && TargetMultiarchTriple.empty()) ||
++      llvm::sys::fs::exists(Base + Suffix + "/" + GCCTriple + IncludeSuffix)) {
++    addSystemInclude(DriverArgs,
++                     CC1Args, Base + Suffix + "/" + GCCTriple + IncludeSuffix);
++  } else {
++    addSystemInclude(DriverArgs, CC1Args,
++                     Base + "/" + GCCMultiarchTriple + Suffix + IncludeSuffix);
++    addSystemInclude(DriverArgs, CC1Args,
++                     Base + "/" + TargetMultiarchTriple + Suffix);
++  }
++
++  addSystemInclude(DriverArgs, CC1Args, Base + "/backward");
++  addSystemInclude(DriverArgs, CC1Args, Base + Suffix + "/backward");
++  return true;
++}
++
++void
++Solaris::AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs,
++                                      llvm::opt::ArgStringList &CC1Args) const {
+   if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
+       DriverArgs.hasArg(options::OPT_nostdincxx))
+     return;
+ 
+-  // Include the support directory for things like xlocale and fudged system
+-  // headers.
+-  addSystemInclude(DriverArgs, CC1Args, "/usr/include/c++/v1/support/solaris");
++  const Driver &D = getDriver();
+ 
+-  if (GCCInstallation.isValid()) {
+-    GCCVersion Version = GCCInstallation.getVersion();
+-    addSystemInclude(DriverArgs, CC1Args,
+-                     getDriver().SysRoot + "/usr/gcc/" +
+-                     Version.MajorStr + "." +
+-                     Version.MinorStr +
+-                     "/include/c++/" + Version.Text);
+-    addSystemInclude(DriverArgs, CC1Args,
+-                     getDriver().SysRoot + "/usr/gcc/" + Version.MajorStr +
+-                     "." + Version.MinorStr + "/include/c++/" +
+-                     Version.Text + "/" +
+-                     GCCInstallation.getTriple().str());
++  // Check for Clang libc++
++  if (GetCXXStdlibType(DriverArgs) == ToolChain::CST_Libcxx) {
++    if (!Solaris::SupportsClangLibCPlusPlus) {
++      D.Diag(diag::err_drv_invalid_stdlib_name) << "libc++";
++      return;
++    }
++
++    StringRef IncludePath = "/usr/include/libc++/v1";
++    if (!llvm::sys::fs::exists(IncludePath)) {
++      D.Diag(diag::err_drv_no_such_file) << IncludePath;
++      return;
++    }
++
++    addSystemInclude(DriverArgs, CC1Args, IncludePath);
++    return;
++  }
++
++  for (std::vector<std::string>::const_iterator B =
++       getGCCIncludeDirs().begin(), E = getGCCIncludeDirs().end();
++       B != E; ++B) {
++    llvm::Twine IncludePath((*B));
++    addSystemInclude(DriverArgs, CC1Args, IncludePath);
++  }
++}
++
++void
++Solaris::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
++                                   ArgStringList &CC1Args) const {
++  const Driver &D = getDriver();
++
++  if (DriverArgs.hasArg(options::OPT_nostdinc))
++    return;
++
++  std::string SysRoot = computeSysRoot();
++
++  if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
++    SmallString<PATH_MAX> P(D.ResourceDir);
++    llvm::sys::path::append(P, "/include");
++    addSystemInclude(DriverArgs, CC1Args, P.str());
++  }
++
++  if (DriverArgs.hasArg(options::OPT_nostdlibinc))
++    return;
++
++  StringRef CIncludeDirs(C_INCLUDE_DIRS);
++  if (CIncludeDirs != "") {
++    SmallVector<StringRef, 5> dirs;
++    CIncludeDirs.split(dirs, ":");
++    for (SmallVectorImpl<StringRef>::iterator I = dirs.begin(), E = dirs.end();
++         I != E; ++I) {
++      StringRef Prefix =
++        llvm::sys::path::is_absolute(*I) ? StringRef(SysRoot) : "";
++      addExternCSystemInclude(DriverArgs, CC1Args, Prefix + *I);
++    }
++  }
++
++  addExternCSystemInclude(DriverArgs, CC1Args, "/usr/include");
++}
++
++void
++Solaris::addClangTargetOptions(const ArgList &DriverArgs,
++                               ArgStringList &CC1Args) const {
++  const llvm::Triple& TT = getTriple();
++  llvm::Triple::ArchType Arch = TT.getArch();
++
++  if (Arg *A = DriverArgs.getLastArg(options::OPT_fuse_init_array))
++    DriverArgs.ClaimAllArgs(options::OPT_fuse_init_array);
++
++  // Always use .init_array/.fini_array on Solaris. The Solaris
++  // linker can't do .ctors/.dtors or .init/.fini for that matter.
++  CC1Args.push_back("-fuse-init-array");
++
++  if (Arg *A = DriverArgs.getLastArg(options::OPT_fabi_version_EQ)) {
++    StringRef V = A->getValue();
++    if (!V.empty()) {
++      std::string fabi_version = "-fabi-version=";
++      fabi_version += V.str();
++      CC1Args.push_back(DriverArgs.MakeArgString(fabi_version.c_str()));
++    } else {
++      std::string fabi_version = "-fabi-version=4";
++      CC1Args.push_back(DriverArgs.MakeArgString(fabi_version.c_str()));
++    }
++  } else {
++    CC1Args.push_back(DriverArgs.MakeArgString("-fabi-version=4"));
++  }
++
++  DriverArgs.ClaimAllArgs(options::OPT_fabi_version_EQ);
++
++  if (Arch == llvm::Triple::sparc || Arch == llvm::Triple::sparcv9) {
++    CC1Args.push_back(DriverArgs.MakeArgString("-target-feature"));
++    CC1Args.push_back(DriverArgs.MakeArgString("+hwcap"));
++  }
++
++  bool SeenVIS = false;
++  bool SeenVIS2 = false;
++  bool SeenVIS3 = false;
++
++  bool DoneVIS = false;
++  bool DoneVIS2 = false;
++  bool DoneVIS3 = false;
++
++  bool DoneMTune = false;
++
++  if (Arg *A = DriverArgs.getLastArg(options::OPT_mtune_EQ)) {
++    StringRef V = A->getValue();
++    if (!V.empty())
++      mtune = V.str();
++    else
++      mtune = "ultrasparc";
++
++    if (Arch == llvm::Triple::sparc || Arch == llvm::Triple::sparcv9) {
++      if ((mtune == "ultrasparc") || (mtune == "ultrasparc2") ||
++          (mtune == "vis")) {
++        SeenVIS = true;
++      } else if ((mtune == "ultrasparc3") || (mtune == "vis2")) {
++        SeenVIS = true;
++        SeenVIS2 = true;
++      } else {
++        SeenVIS = true;
++        SeenVIS2 = true;
++        SeenVIS3 = true;
++      }
++
++      if (!DoneMTune) {
++        if (SeenVIS3 && !DoneVIS3) {
++          CC1Args.push_back(DriverArgs.MakeArgString("-target-feature"));
++          CC1Args.push_back(DriverArgs.MakeArgString("+vis3"));
++          DoneVIS3 = true;
++          DoneVIS2 = true;
++          DoneVIS = true;
++        }
++
++        if (SeenVIS2 && !DoneVIS2) {
++          CC1Args.push_back(DriverArgs.MakeArgString("-target-feature"));
++          CC1Args.push_back(DriverArgs.MakeArgString("+vis2"));
++          DoneVIS2 = true;
++          DoneVIS = true;
++        }
++
++        if (SeenVIS && !DoneVIS) {
++          CC1Args.push_back(DriverArgs.MakeArgString("-target-feature"));
++          CC1Args.push_back(DriverArgs.MakeArgString("+vis"));
++          DoneVIS = true;
++        }
++
++        DoneMTune = true;
++      }
++    }
++  }
++
++  if (Arch == llvm::Triple::sparc || Arch == llvm::Triple::sparcv9) {
++    if (Arg *A = DriverArgs.getLastArg(options::OPT_mvis)) {
++      SeenVIS = !DoneVIS;
++      if (!DoneVIS) {
++        CC1Args.push_back(DriverArgs.MakeArgString("-target-feature"));
++        CC1Args.push_back(DriverArgs.MakeArgString("+vis"));
++        DoneVIS = true;
++      }
++    }
++
++    if (Arg *A = DriverArgs.getLastArg(options::OPT_mvis2)) {
++      SeenVIS2 = !DoneVIS2;
++      if (!DoneVIS2) {
++        CC1Args.push_back(DriverArgs.MakeArgString("-target-feature"));
++        CC1Args.push_back(DriverArgs.MakeArgString("+vis2"));
++        DoneVIS2 = true;
++        DoneVIS = true;
++      }
++    }
++
++    if (Arg *A = DriverArgs.getLastArg(options::OPT_mvis3)) {
++      SeenVIS3 = !DoneVIS3;
++      if (!DoneVIS3) {
++        CC1Args.push_back(DriverArgs.MakeArgString("-target-feature"));
++        CC1Args.push_back(DriverArgs.MakeArgString("+vis3"));
++        DoneVIS3 = true;
++        DoneVIS2 = true;
++        DoneVIS = true;
++      }
++    }
++  }
++}
++
++void
++Solaris::findGCCMajorMinor() const {
++  // FIXME: Add 5.X after testing the ABI.
++  static const char* const GCCMM[] = { "4.8", "4.9" };
++
++  const char* P;
++  std::string Path;
++
++  Path.reserve(std::string::size_type(PATH_MAX));
++
++  for (int I = (llvm::array_lengthof(GCCMM) - 1); I >= 0; --I) {
++    if ((P = GCCMM[I]) != NULL) {
++      Path = GCCInstallDir;
++      Path.append(P);
++      Path.append("/");
++
++      if (llvm::sys::fs::exists(Path.c_str())) {
++        GCCMajorMinor = P;
++        break;
++      }
++    }
++  }
++}
++
++void
++Solaris::findGCCMajorMinorMicro(const llvm::Triple& T) const {
++  // FIXME: Add 5.X after testing the ABI.
++  static const char* const GCCMMM[] = { "4.8.2", "4.9.3", "4.9.4" };
++
++  const char* P;
++  std::string Path;
++  std::string TripleString = llvm::sys::getDefaultTargetTriple();
++  llvm::Triple::ArchType Arch = T.getArch();
++
++  // GCC4 on Solaris is multilib 32/64.
++  // GCC5 (not supported here yet) on Solaris is multilib 64/32.
++  if (GCCMajorMinor[0] == '4') {
++    if (TripleString.find("x86_64") != std::string::npos)
++      TripleString.replace(0U, 6U, std::string("i386"));
++    else if (TripleString.find("sparcv9") != std::string::npos)
++      TripleString.replace(0U, 7U, std::string("sparc"));
++  }
++
++  Path.reserve(std::string::size_type(PATH_MAX));
++
++  for (int I = (llvm::array_lengthof(GCCMMM) - 1); I >= 0; --I) {
++    if ((P = GCCMMM[I]) != NULL) {
++      if ((P[0] == GCCMajorMinor[0]) && (P[2] == GCCMajorMinor[2])) {
++        Path = GCCInstallDir;
++        Path.append("/");
++        Path.append(GCCMajorMinor);
++        Path.append("/lib/gcc/");
++        Path.append(TripleString);
++        Path.append("/");
++        Path.append(P);
++
++        if (llvm::sys::fs::exists(Path.c_str())) {
++          std::string Test;
++          // Check if this is a real GCC installation and not just
++          // an empty directory tree
++          switch (Arch) {
++          case llvm::Triple::x86:
++          case llvm::Triple::sparc:
++            Test = Path + "/crtbegin.o";
++            break;
++          case llvm::Triple::x86_64:
++            Test = Path + "/amd64/crtbegin.o";
++            break;
++          case llvm::Triple::sparcv9:
++            Test = Path + "/sparcv9/crtbegin.o";
++            break;
++          default:
++            break;
++          }
++
++          if (llvm::sys::fs::exists(Test.c_str())) {
++            GCCMajorMinorMicro = P;
++            break;
++          }
++        }
++      }
++    }
++  }
++}
++
++void
++Solaris::findSpecifiedGCCToolchain(const char *StartingPath,
++                                   const llvm::Triple &Triple,
++                                   const llvm::opt::ArgList &Args) const {
++  DIR *TopLD = 0;
++  DIR *LibLD = 0;
++  DIR *GccLD = 0;
++  DIR *TripleLD = 0;
++  struct dirent *TopDE = 0;
++  struct dirent *LibDE = 0;
++  struct dirent *GccDE = 0;
++  struct dirent *TripleDE = 0;
++  std::string LibDir;
++  std::string GccDir;
++  std::string TripleDir;
++  std::string TripleVersionDir;
++  const char *DName;
++
++  assert(StartingPath && "Invalid GCC Toolchain starting search path!");
++
++  GCCMajorMinor = "";
++  GCCMajorMinorMicro = "";
++  UseSpecifiedGCCToolChainPath = false;
++
++  LibDir.reserve(std::string::size_type(PATH_MAX));
++  GccDir.reserve(std::string::size_type(PATH_MAX));
++  TripleDir.reserve(std::string::size_type(PATH_MAX));
++  TripleVersionDir.reserve(std::string::size_type(PATH_MAX));
++
++  if (llvm::sys::fs::exists(StartingPath) &&
++      llvm::sys::fs::is_directory(StartingPath)) {
++    TopLD = opendir(StartingPath);
++    assert(TopLD && "Cannot obtain a valid toplevel DIR handle!");
++
++    while ((TopDE = readdir(TopLD)) != NULL) {
++      if (TopDE->d_name[0] == '.')
++        continue;
++
++      DName = static_cast<const char*>(&TopDE->d_name[0]);
++      if (std::strcmp(DName, "lib") == 0) {
++        LibDir = StartingPath;
++        LibDir.append("/");
++        LibDir.append(DName);
++
++        if (!llvm::sys::fs::is_directory(LibDir.c_str()))
++          continue;
++
++        LibLD = opendir(LibDir.c_str());
++        assert(LibLD && "Could not obtain a valid lib DIR handle!");
++
++        while ((LibDE = readdir(LibLD)) != NULL) {
++          if (LibDE->d_name[0] == '.')
++            continue;
++
++          DName = static_cast<const char*>(&LibDE->d_name[0]);
++          if (std::strcmp(DName, "gcc") == 0) {
++            GccDir = LibDir;
++            GccDir.append("/");
++            GccDir.append(DName);
++
++            if (!llvm::sys::fs::is_directory(GccDir.c_str()))
++              continue;
++
++            GccLD = opendir(GccDir.c_str());
++            assert(GccLD && "Could not obtain a valid gcc DIR handle!");
++
++            while ((GccDE = readdir(GccLD)) != NULL) {
++              if (GccDE->d_name[0] == '.')
++                continue;
++
++              DName = static_cast<const char*>(&GccDE->d_name[0]);
++              TripleDir = GccDir;
++              TripleDir.append("/");
++              TripleDir.append(DName);
++
++              if (!llvm::sys::fs::is_directory(TripleDir.c_str()))
++                continue;
++
++              if ((std::strncmp(DName, "sparc", 5) == 0) ||
++                  (std::strncmp(DName, "i386", 4) == 0) ||
++                  (std::strncmp(DName, "sparcv9", 7) == 0) ||
++                  (std::strncmp(DName, "x86_64", 6) == 0)) {
++                TripleLD = opendir(TripleDir.c_str());
++                assert(TripleLD &&
++                       "Could not obtain a valid Triple DIR handle!");
++
++                while ((TripleDE = readdir(TripleLD)) != NULL) {
++                  if (TripleDE->d_name[0] == '.')
++                    continue;
++
++                  DName = static_cast<const char*>(&TripleDE->d_name[0]);
++                  TripleVersionDir = TripleDir;
++                  TripleVersionDir.append("/");
++                  TripleVersionDir.append(DName);
++
++                  if (!llvm::sys::fs::is_directory(TripleVersionDir.c_str()))
++                    continue;
++
++                  if ((std::isdigit(DName[0])) && (DName[1] == '.') &&
++                      (std::isdigit(DName[2])) && (DName[3] == '.') &&
++                      (std::isdigit(DName[4])) && (DName[5] == '\0')) {
++                    GCCMajorMinorMicro = DName;
++                    GCCMajorMinor = GCCMajorMinorMicro.substr(0, 3);
++                    UseSpecifiedGCCToolChainPath = true;
++                    goto done;
++                  }
++                }
++              }
++            }
++          }
++        }
++      }
++    }
++  }
++
++done:
++  if (TripleLD) {
++    rewinddir(TripleLD);
++    closedir(TripleLD);
++  }
++
++  if (GccLD) {
++    rewinddir(GccLD);
++    closedir(GccLD);
++  }
++
++  if (LibLD) {
++    rewinddir(LibLD);
++    closedir(LibLD);
++  }
++
++  if (TopLD) {
++    rewinddir(TopLD);
++    closedir(TopLD);
++  }
++}
++
++void
++Solaris::findGCCIncludeDirs(const llvm::Triple &Triple,
++                            const llvm::opt::ArgList &Args) const {
++  std::string GCCInstallPath;
++  if (UseSpecifiedGCCToolChainPath)
++    GCCInstallPath = GCCInstallDir;
++  else
++    GCCInstallPath = GCCInstallDir + GCCMajorMinor;
++
++  std::string GCCIncludeDir =
++    GCCInstallPath + "/include/c++/" + GCCMajorMinorMicro;
++  GCCIncludeDirs.push_back(GCCIncludeDir);
++
++  llvm::Triple::ArchType Arch = Triple.getArch();
++  GCCIncludeDir += "/";
++
++  switch (Arch) {
++  case llvm::Triple::x86:
++    GCCIncludeDir += Triple.getTriple();
++    if (Arg *A = Args.getLastArg(options::OPT_m64))
++      GCCIncludeDir += "/amd64";
++    break;
++  case llvm::Triple::sparc:
++    GCCIncludeDir += Triple.getTriple();
++    if (Arg *A = Args.getLastArg(options::OPT_m64))
++      GCCIncludeDir += "/sparcv9";
++    break;
++  case llvm::Triple::x86_64:
++    GCCIncludeDir += "i386-pc-";
++    GCCIncludeDir += Triple.getOSName();
++    if (Arg *A = Args.getLastArg(options::OPT_m64))
++      GCCIncludeDir += "/amd64";
++    break;
++  case llvm::Triple::sparcv9:
++    GCCIncludeDir += "sparc-sun-";
++    GCCIncludeDir += Triple.getOSName();
++    if (Arg *A = Args.getLastArg(options::OPT_m64))
++      GCCIncludeDir += "/sparcv9";
++    break;
++  default:
++    getDriver().Diag(diag::err_target_unsupported_arch)
++      << Triple.getArchName() << Triple.getTriple();
++    break;
++  }
++
++  GCCIncludeDirs.push_back(GCCIncludeDir);
++
++  GCCIncludeDir = GCCInstallPath + "/include/c++/" +
++    GCCMajorMinorMicro + "/backward";
++
++  GCCIncludeDirs.push_back(GCCIncludeDir);
++}
++
++void
++Solaris::findGCCInternalLibDir(const llvm::Triple &Triple,
++                               const llvm::opt::ArgList &Args) const {
++  std::string GCCInstallPath;
++  if (UseSpecifiedGCCToolChainPath)
++    GCCInstallPath = GCCInstallDir;
++  else
++    GCCInstallPath = GCCInstallDir + GCCMajorMinor;
++
++  GCCInternalLibDir = GCCInstallPath + "/lib/gcc/";
++
++  llvm::Triple::ArchType Arch = Triple.getArch();
++
++  switch (Arch) {
++  case llvm::Triple::x86:
++    GCCInternalLibDir += Triple.getTriple();
++    GCCInternalLibDir += "/";
++    GCCInternalLibDir += GCCMajorMinorMicro;
++    if (Arg *A = Args.getLastArg(options::OPT_m64)) {
++      GCCInternalMultiLibDir = GCCInternalLibDir;
++      GCCInternalLibDir += "/amd64";
++    } else if (Arg *A = Args.getLastArg(options::OPT_m32)) {
++      GCCInternalMultiLibDir = GCCInternalLibDir;
++      GCCInternalMultiLibDir += "/amd64";
++    } else {
++      GCCInternalMultiLibDir = GCCInternalLibDir;
++      GCCInternalMultiLibDir += "/amd64";
++    }
++
++    break;
++  case llvm::Triple::sparc:
++    GCCInternalLibDir += Triple.getTriple();
++    GCCInternalLibDir += "/";
++    GCCInternalLibDir += GCCMajorMinorMicro;
++    if (Arg *A = Args.getLastArg(options::OPT_m64)) {
++      GCCInternalMultiLibDir = GCCInternalLibDir;
++      GCCInternalLibDir += "/sparcv9";
++    } else if (Arg *A = Args.getLastArg(options::OPT_m32)) {
++      GCCInternalMultiLibDir = GCCInternalLibDir;
++      GCCInternalMultiLibDir += "/sparcv9";
++    } else {
++      GCCInternalMultiLibDir = GCCInternalLibDir;
++      GCCInternalMultiLibDir += "/sparcv9";
++    }
++    break;
++  case llvm::Triple::x86_64:
++    GCCInternalLibDir += "i386-pc-";
++    GCCInternalLibDir += Triple.getOSName();
++    GCCInternalLibDir += "/";
++    GCCInternalLibDir += GCCMajorMinorMicro;
++    GCCInternalMultiLibDir = GCCInternalLibDir;
++    if (Arg *A = Args.getLastArg(options::OPT_m64))
++      GCCInternalLibDir += "/amd64";
++    else if (Arg *A = Args.getLastArg(options::OPT_m32))
++      GCCInternalMultiLibDir += "/amd64";
++    else
++      GCCInternalLibDir += "/amd64";
++    break;
++  case llvm::Triple::sparcv9:
++    GCCInternalLibDir += "sparc-sun-";
++    GCCInternalLibDir += Triple.getOSName();
++    GCCInternalLibDir += "/";
++    GCCInternalLibDir += GCCMajorMinorMicro;
++    GCCInternalMultiLibDir = GCCInternalLibDir;
++    if (Arg *A = Args.getLastArg(options::OPT_m64))
++      GCCInternalLibDir += "/sparcv9";
++    else if (Arg *A = Args.getLastArg(options::OPT_m32))
++      GCCInternalMultiLibDir += "/sparcv9";
++    else
++      GCCInternalLibDir += "/sparcv9";
++    break;
++  default:
++    getDriver().Diag(diag::err_target_unsupported_arch)
++      << Triple.getArchName() << Triple.getTriple();
++    break;
++  }
++}
++
++
++void
++Solaris::print(raw_ostream &OS) const {
++  OS << "UseGnuAs: " << (UseGnuAs ? "true" : "false") << "\n";
++  OS << "UseGnuLd: " << (UseGnuLd ? "true" : "false") << "\n";
++  OS << "UseGoldLd: " << (UseGoldLd ? "true" : "false") << "\n";
++  OS << "UseSunLd: " << (UseSunLd ? "true" : "false") << "\n";
++  OS << "UseMediatedGCCToolChainPath: "
++    << (UseMediatedGCCToolChainPath ? "true" : "false") << "\n";
++  OS << "UseSpecifiedGCCToolChainPath: "
++    << (UseSpecifiedGCCToolChainPath ? "true" : "false") << "\n";
++  OS << "GCCInstallDir: " << GCCInstallDir.c_str() << "\n";
++  OS << "GCCMajorMinor: " << GCCMajorMinor.c_str() << "\n";
++  OS << "GCCMajorMinorMicro: " << GCCMajorMinorMicro.c_str() << "\n";
++  OS << "GCCInternalLibDir: " << GCCInternalLibDir.c_str() << "\n";
++  OS << "GCCInternalMultiLibDir: " << GCCInternalMultiLibDir.c_str() << "\n";
++  OS << "GCCIncludeDirs: ";
++
++  if (GCCIncludeDirs.size()) {
++    std::string IncludePath;
++    for (std::vector<std::string>::const_iterator B = GCCIncludeDirs.begin(),
++         E = GCCIncludeDirs.end(); B != E; ++B) {
++      IncludePath = "-I";
++      IncludePath += (*B);
++      OS << IncludePath.c_str() << " ";
++    }
++
++    OS << "\n";
++  }
++
++  OS << "Assembler: " << Assembler.c_str() << "\n";
++  OS << "Linker: " << Linker.c_str() << "\n";
++  OS << "mtune: " << mtune.c_str() << "\n";
++  OS << "march: " << march.c_str() << "\n";
++  OS << "mcpu: " << mcpu.c_str() << "\n";
++
++  if (ExtraOpts.size()) {
++    OS << "ExtraOpts: ";
++    for (std::vector<std::string>::const_iterator B = ExtraOpts.begin(),
++         E = ExtraOpts.end(); B != E; ++B) {
++      OS << (*B).c_str() << " ";
++    }
++
++    OS << "\n";
++  }
++
++  OS << "Valid: " << (IsValid ? "true" : "false") << "\n";
++}
++
++Tool *Solaris::buildAssembler() const {
++  return new tools::solaris::Assembler(*this);
++}
++
++Tool *Solaris::buildLinker() const {
++  return new tools::solaris::Linker(*this);
++}
++
++void Solaris::validate() {
++  IsValid = llvm::sys::fs::exists(GCCInstallDir.c_str());
++  if (!IsValid) return;
++  IsValid = llvm::sys::fs::exists(GCCInternalLibDir.c_str());
++  if (!IsValid) return;
++  IsValid = llvm::sys::fs::exists(GCCInternalMultiLibDir.c_str());
++  if (!IsValid) return;
++
++  for (std::vector<std::string>::const_iterator B = GCCIncludeDirs.begin(),
++       E = GCCIncludeDirs.end(); B != E; ++B) {
++    IsValid = llvm::sys::fs::exists((*B).c_str());
++    if (!IsValid) return;
+   }
+ }
+ 
+@@ -3404,6 +4137,27 @@
+   UbuntuVivid,
+   UbuntuWily,
+   UbuntuXenial,
++  Solaris_11,
++  Solaris_11_1,
++  Solaris_11_2,
++  Solaris_11_3,
++  Solaris_11_4,
++  Solaris_11_5,
++  Solaris_11_6,
++  Solaris_11_7,
++  Solaris_11_8,
++  Solaris_11_9,
++  Solaris_12,
++  Solaris_12_1,
++  Solaris_12_2,
++  Solaris_12_3,
++  Solaris_12_4,
++  Solaris_12_5,
++  Solaris_12_6,
++  Solaris_12_7,
++  Solaris_12_8,
++  Solaris_12_9,
++  Solaris_13,
+   UnknownDistro
+ };
+ 
+@@ -3421,6 +4175,10 @@
+   return Distro >= UbuntuHardy && Distro <= UbuntuXenial;
+ }
+ 
++static bool IsSolaris(enum Distro Distro) {
++  return Distro >= Solaris_11 && Distro <= Solaris_13;
++}
++
+ static Distro DetectDistro(const Driver &D, llvm::Triple::ArchType Arch) {
+   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> File =
+       llvm::MemoryBuffer::getFile("/etc/lsb-release");
+@@ -3488,6 +4246,59 @@
+     return UnknownDistro;
+   }
+ 
++  File = llvm::MemoryBuffer::getFile("/etc/release");
++  if (File) {
++    StringRef Data = File.get()->getBuffer();
++    SmallVector<StringRef, 8> Lines;
++    Data.split(Lines, "\n");
++    for (unsigned I = 0, S = Lines.size(); I != S; ++I) {
++      if (Lines[I].find("Oracle Solaris") != std::string::npos) {
++        if (Lines[I].find("Solaris 11.0") != std::string::npos)
++          return Solaris_11;
++        else if (Lines[I].find("Solaris 11.1") != std::string::npos)
++          return Solaris_11_1;
++        else if (Lines[I].find("Solaris 11.2") != std::string::npos)
++          return Solaris_11_2;
++        else if (Lines[I].find("Solaris 11.3") != std::string::npos)
++          return Solaris_11_3;
++        else if (Lines[I].find("Solaris 11.4") != std::string::npos)
++          return Solaris_11_4;
++        else if (Lines[I].find("Solaris 11.5") != std::string::npos)
++          return Solaris_11_5;
++        else if (Lines[I].find("Solaris 11.6") != std::string::npos)
++          return Solaris_11_6;
++        else if (Lines[I].find("Solaris 11.7") != std::string::npos)
++          return Solaris_11_7;
++        else if (Lines[I].find("Solaris 11.8") != std::string::npos)
++          return Solaris_11_8;
++        else if (Lines[I].find("Solaris 11.9") != std::string::npos)
++          return Solaris_11_9;
++        else if (Lines[I].find("Solaris 12.0") != std::string::npos)
++          return Solaris_12;
++        else if (Lines[I].find("Solaris 12.1") != std::string::npos)
++          return Solaris_12_1;
++        else if (Lines[I].find("Solaris 12.2") != std::string::npos)
++          return Solaris_12_2;
++        else if (Lines[I].find("Solaris 12.3") != std::string::npos)
++          return Solaris_12_3;
++        else if (Lines[I].find("Solaris 12.4") != std::string::npos)
++          return Solaris_12_4;
++        else if (Lines[I].find("Solaris 12.5") != std::string::npos)
++          return Solaris_12_5;
++        else if (Lines[I].find("Solaris 12.6") != std::string::npos)
++          return Solaris_12_6;
++        else if (Lines[I].find("Solaris 12.7") != std::string::npos)
++          return Solaris_12_7;
++        else if (Lines[I].find("Solaris 12.8") != std::string::npos)
++          return Solaris_12_8;
++        else if (Lines[I].find("Solaris 12.9") != std::string::npos)
++          return Solaris_12_9;
++      }
++    }
++
++    return UnknownDistro;
++  }
++
+   if (D.getVFS().exists("/etc/SuSE-release"))
+     return OpenSUSE;
+ 
+###
+--- tools/clang/lib/Driver/ToolChains.h	2016-02-16 14:56:48.000000000 -0500
++++ tools/clang/lib/Driver/ToolChains.h	2016-05-08 23:19:20.571431701 -0400
+@@ -615,24 +615,111 @@
+   Tool *buildLinker() const override;
+ };
+ 
+-class LLVM_LIBRARY_VISIBILITY Solaris : public Generic_GCC {
++class LLVM_LIBRARY_VISIBILITY Solaris : public Generic_ELF {
+ public:
+   Solaris(const Driver &D, const llvm::Triple &Triple,
+           const llvm::opt::ArgList &Args);
+ 
+-  bool IsIntegratedAssemblerDefault() const override { return true; }
++  bool IsIntegratedAssemblerDefault() const override { return !UseGnuAs; }
+ 
+-  void AddClangCXXStdlibIncludeArgs(
+-      const llvm::opt::ArgList &DriverArgs,
+-      llvm::opt::ArgStringList &CC1Args) const override;
++  std::string computeSysRoot() const;
+ 
+-  unsigned GetDefaultDwarfVersion() const override { return 2; }
++  bool addLibStdCXXIncludePaths(Twine Base, Twine Suffix,
++                                StringRef GCCTriple,
++                                StringRef GCCMultiarchTriple,
++                                StringRef TargetMultiarchTriple,
++                                Twine IncludeSuffix,
++                                const llvm::opt::ArgList &DriverArgs,
++                                llvm::opt::ArgStringList &CC1Args) const;
++
++  void addLibStdCXXIncludePaths(Twine Base, Twine TargetArchDir,
++                                const llvm::opt::ArgList &DriverArgs,
++                                llvm::opt::ArgStringList &CC1Args) const;
++
++  void AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs,
++                                    llvm::opt::ArgStringList &CC1Args) const override;
++
++  void AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs,
++                                 llvm::opt::ArgStringList &CC1Args) const override;
++
++  void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
++                             llvm::opt::ArgStringList &CC1Args) const override;
++
++  void findGCCMajorMinor() const;
++  void findGCCMajorMinorMicro(const llvm::Triple &Triple) const;
++  void findGCCIncludeDirs(const llvm::Triple &Triple,
++                          const llvm::opt::ArgList &Args) const;
++  void findGCCInternalLibDir(const llvm::Triple &Triple,
++                             const llvm::opt::ArgList &Args) const;
++  void findSpecifiedGCCToolchain(const char *StartingPath,
++                                 const llvm::Triple &Triple,
++                                 const llvm::opt::ArgList &Args) const;
++
++  StringRef getAssembler() const { return Assembler.c_str(); }
++  StringRef getLinker() const { return Linker.c_str(); }
++  StringRef getGCCInstallDir() const { return GCCInstallDir.c_str(); }
++  StringRef getGCCMajorMinor() const { return GCCMajorMinor.c_str(); }
++  StringRef getMArch() const { return march.c_str(); }
++  StringRef getMTune() const { return mtune.c_str(); }
++  StringRef getMCpu() const { return mcpu.c_str(); }
++  StringRef getGCCInternalLibDir() const { return GCCInternalLibDir; }
++
++  StringRef getGCCInternalMultiLibDir() const {
++    return GCCInternalMultiLibDir;
++  }
++
++  StringRef getGCCMajorMinorMicro() const {
++    return GCCMajorMinorMicro.c_str();
++  }
++
++  const std::vector<std::string> &getGCCIncludeDirs() const {
++    return GCCIncludeDirs;
++  }
++
++  const std::vector<std::string> &getExtraOpts() const {
++    return ExtraOpts;
++  }
++
++  bool isValid() const { return IsValid; }
++
++  void print(raw_ostream &OS) const;
++
++  unsigned GetDefaultDwarfVersion() const override { return 4; }
+ 
+ protected:
+   Tool *buildAssembler() const override;
+   Tool *buildLinker() const override;
++  void validate();
++
++private:
++  bool UseGnuAs;
++  bool UseGnuLd;
++  bool UseGoldLd;
++  bool UseSunLd;
++  mutable bool UseMediatedGCCToolChainPath;
++  mutable bool UseSpecifiedGCCToolChainPath;
++  bool IsValid;
++
++protected:
++  mutable std::string GCCInstallDir;
++  mutable std::string GCCMajorMinor;
++  mutable std::string GCCMajorMinorMicro;
++  mutable std::string GCCInternalLibDir;
++  mutable std::string GCCInternalMultiLibDir;
++  mutable std::vector<std::string> GCCIncludeDirs;
++
++  mutable std::string Assembler;
++  mutable std::string Linker;
++  mutable std::string mtune;
++  mutable std::string march;
++  mutable std::string mcpu;
++
++  mutable std::vector<std::string> ExtraOpts;
++  static const char *MediatedGCCToolChainPath;
++  static bool SupportsClangLibCPlusPlus;
+ };
+ 
++
+ class LLVM_LIBRARY_VISIBILITY MinGW : public ToolChain {
+ public:
+   MinGW(const Driver &D, const llvm::Triple &Triple,
+###
+--- tools/clang/lib/Driver/Tools.cpp	2016-02-12 14:51:41.000000000 -0800
++++ tools/clang/lib/Driver/Tools.cpp	2016-07-18 19:13:48.364415520 -0700
+@@ -43,15 +43,22 @@
+ #include "llvm/Support/raw_ostream.h"
+ #include "llvm/Support/TargetParser.h"
+ 
+-#ifdef LLVM_ON_UNIX
+-#include <unistd.h> // For getuid().
+-#endif
+-
+ using namespace clang::driver;
+ using namespace clang::driver::tools;
+ using namespace clang;
+ using namespace llvm::opt;
+ 
++#ifdef LLVM_ON_UNIX
++#include <unistd.h> // For getuid().
++#endif
++
++#include <cstdlib>
++#include <climits>
++
++static std::tuple<llvm::Reloc::Model, unsigned, bool>
++ParsePICArgs(const ToolChain &ToolChain, const llvm::Triple &Triple,
++             const ArgList &Args);
++
+ static void handleTargetFeaturesGroup(const ArgList &Args,
+                                       std::vector<const char *> &Features,
+                                       OptSpecifier Group) {
+@@ -74,11 +81,15 @@
+                                          const llvm::Triple &Triple) {
+   if (Triple.getArch() == llvm::Triple::sparcv9) {
+     return llvm::StringSwitch<const char *>(Name)
++          .Case("v9", "-Av9")
++          .Case("ultrasparc", "-Av9a")
++          .Case("ultrasparc2", "-Av9a")
++          .Case("ultrasparc3", "-Av9b")
+           .Case("niagara", "-Av9b")
+           .Case("niagara2", "-Av9b")
+           .Case("niagara3", "-Av9d")
+           .Case("niagara4", "-Av9d")
+-          .Default("-Av9");
++          .Default("-Av9a");
+   } else {
+     return llvm::StringSwitch<const char *>(Name)
+           .Case("v8", "-Av8")
+@@ -89,17 +100,23 @@
+           .Case("sparclite86x", "-Asparclite")
+           .Case("sparclet", "-Asparclet")
+           .Case("tsc701", "-Asparclet")
+-          .Case("v9", "-Av8plus")
+-          .Case("ultrasparc", "-Av8plus")
+-          .Case("ultrasparc3", "-Av8plus")
++          .Case("ultrasparc", "-Av8plusa")
++          .Case("ultrasparc2", "-Av8plusa")
++          .Case("ultrasparc3", "-Av8plusb")
+           .Case("niagara", "-Av8plusb")
+           .Case("niagara2", "-Av8plusb")
+           .Case("niagara3", "-Av8plusd")
+           .Case("niagara4", "-Av8plusd")
+-          .Default("-Av8");
++          .Default("-Av8plusa");
+   }
+ }
+ 
++static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
++                      ArgStringList &CmdArgs, const ArgList &Args);
++
++static void AddLibgcc(const Driver &D, ArgStringList &CmdArgs,
++                      const ArgList &Args, const std::string& Exec);
++
+ /// CheckPreprocessingOptions - Perform some validation of preprocessing
+ /// arguments that is shared with gcc.
+ static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
+@@ -266,6 +283,27 @@
+     addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
+ }
+ 
++static void AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
++                             ArgStringList &CmdArgs) {
++  llvm::Reloc::Model RelocationModel;
++  unsigned PICLevel = 1;
++  bool IsPIE = false;
++
++  std::tie(RelocationModel, PICLevel, IsPIE) =
++    ParsePICArgs(ToolChain, ToolChain.getTriple(), Args);
++
++  if (ToolChain.getTriple().getOS() == llvm::Triple::Solaris) {
++    if ((RelocationModel != llvm::Reloc::Static) &&
++        (RelocationModel != llvm::Reloc::DynamicNoPIC))
++      CmdArgs.push_back("-KPIC");
++
++    return;
++  }
++
++  if (RelocationModel != llvm::Reloc::Static)
++    CmdArgs.push_back("-KPIC");
++}
++
+ /// \brief Determine whether Objective-C automated reference counting is
+ /// enabled.
+ static bool isObjCAutoRefCount(const ArgList &Args) {
+@@ -1601,8 +1639,127 @@
+   }
+ }
+ 
+-static const char *getX86TargetCPU(const ArgList &Args,
+-                                   const llvm::Triple &Triple) {
++const char *sparc::getSparcTargetCPU(const llvm::opt::ArgList &Args,
++                                     const llvm::Triple &Triple) {
++  if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
++    StringRef AV = A->getValue();
++    if (AV == "native") {
++      std::string CPU = llvm::sys::getHostCPUName().str();
++      if (CPU.find("UltraSPARC-IV") != std::string::npos)
++        return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9c" : "v8plusc";
++      else if (CPU.find("UltraSPARC-III") != std::string::npos)
++        return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9b" : "v8plusb";
++      else if (CPU.find("UltraSPARC-II") != std::string::npos)
++        return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9a" : "v8plusa";
++      else if (CPU.find("UltraSPARC-I") != std::string::npos)
++        return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9" : "v8plus";
++      else if (CPU.find("SPARC-T4") != std::string::npos)
++        return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9v" : "v8plusv";
++      else if (CPU.find("SPARC-T5") != std::string::npos)
++        return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9v" : "v8plusv";
++      else if (CPU.find("SPARC-T6") != std::string::npos)
++        return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9v" : "v8plusv";
++      else if (CPU.find("SPARC-T7") != std::string::npos)
++        return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9v" : "v8plusv";
++      else if (CPU.find("SPARC-M4") != std::string::npos)
++        return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9v" : "v8plusv";
++      else if (CPU.find("SPARC-M5") != std::string::npos)
++        return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9m" : "v8plusm";
++      else if (CPU.find("SPARC-M6") != std::string::npos)
++        return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9m" : "v8plusm";
++      else if (CPU.find("SPARC-M7") != std::string::npos)
++        return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9m" : "v8plusm";
++    } else if (AV == "ultrasparc") {
++      return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9a" : "v8plusa";
++    } else if (AV == "ultrasparc2") {
++      return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9a" : "v8plusa";
++    } else if (AV == "ultrasparc3") {
++      return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9b" : "v8plusb";
++    } else if (AV == "ultrasparc4") {
++      return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9c" : "v8plusc";
++    } else if (AV == "niagara") {
++      return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9b" : "v8plusb";
++    } else if (AV == "niagara2") {
++      return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9b" : "v8plusb";
++    } else if (AV == "niagara3") {
++      return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9b" : "v8plusb";
++    } else if (AV == "niagara4") {
++      return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9b" : "v8plusb";
++    } else if (AV == "sparc4") {
++      return "sparc4";
++    } else if (AV == "sparc5") {
++      return "sparc5";
++    } else if (AV == "generic") {
++      return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9a" : "v8plusa";
++    } else if (AV == "generic32") {
++      return "v8plusa";
++    } else if (AV == "generic64") {
++      return "v9a";
++    }
++  }
++
++  if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
++    StringRef AV = A->getValue();
++    if (AV == "native") {
++      std::string CPU = llvm::sys::getHostCPUName().str();
++      if (CPU.find("UltraSPARC-IV") != std::string::npos)
++        return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9c" : "v8plusc";
++      else if (CPU.find("UltraSPARC-III") != std::string::npos)
++        return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9b" : "v8plusb";
++      else if (CPU.find("UltraSPARC-II") != std::string::npos)
++        return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9a" : "v8plusa";
++      else if (CPU.find("UltraSPARC-I") != std::string::npos)
++        return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9" : "v8plus";
++      else if (CPU.find("SPARC-T4") != std::string::npos)
++        return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9v" : "v8plusv";
++      else if (CPU.find("SPARC-T5") != std::string::npos)
++        return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9m" : "v8plusm";
++      else if (CPU.find("SPARC-T6") != std::string::npos)
++        return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9m" : "v8plusm";
++      else if (CPU.find("SPARC-T7") != std::string::npos)
++        return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9m" : "v8plusm";
++      else if (CPU.find("SPARC-M4") != std::string::npos)
++        return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9v" : "v8plusv";
++      else if (CPU.find("SPARC-M5") != std::string::npos)
++        return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9m" : "v8plusm";
++      else if (CPU.find("SPARC-M6") != std::string::npos)
++        return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9m" : "v8plusm";
++      else if (CPU.find("SPARC-M7") != std::string::npos)
++        return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9m" : "v8plusm";
++    } else if (AV == "ultrasparc") {
++      return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9a" : "v8plusa";
++    } else if (AV == "ultrasparc2") {
++      return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9a" : "v8plusa";
++    } else if (AV == "ultrasparc3") {
++      return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9b" : "v8plusb";
++    } else if (AV == "ultrasparc4") {
++      return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9c" : "v8plusc";
++    } else if (AV == "niagara") {
++      return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9b" : "v8plusb";
++    } else if (AV == "niagara2") {
++      return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9b" : "v8plusb";
++    } else if (AV == "niagara3") {
++      return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9b" : "v8plusb";
++    } else if (AV == "niagara4") {
++      return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9b" : "v8plusb";
++    } else if (AV == "sparc4") {
++      return "sparc4";
++    } else if (AV == "sparc5") {
++      return "sparc5";
++    } else if (AV == "generic") {
++      return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9a" : "v8plusa";
++    } else if (AV == "generic32") {
++      return "v8plusa";
++    } else if (AV == "generic64") {
++      return "v9a";
++    }
++  }
++
++  return Triple.getArch() == llvm::Triple::sparcv9 ?  "v9a" : "v8plusa";
++}
++
++const char *x86::getX86TargetCPU(const llvm::opt::ArgList &Args,
++                                 const llvm::Triple &Triple) {
+   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
+     if (StringRef(A->getValue()) != "native") {
+       if (Triple.isOSDarwin() && Triple.getArchName() == "x86_64h")
+@@ -1616,7 +1773,7 @@
+     //
+     // FIXME: We should also incorporate the detected target features for use
+     // with -native.
+-    std::string CPU = llvm::sys::getHostCPUName();
++    std::string CPU = llvm::sys::getHostCPUName().str();
+     if (!CPU.empty() && CPU != "generic")
+       return Args.MakeArgString(CPU);
+   }
+@@ -1666,6 +1823,10 @@
+   if (Triple.isAndroid())
+     return Is64Bit ? "x86-64" : "i686";
+ 
++  // On Solaris return a target compatible with gas.
++  if (Triple.isOSSolaris())
++    return Is64Bit ? "opteron" : "pentium4";
++
+   // Everything else goes to x86-64 in 64-bit mode.
+   if (Is64Bit)
+     return "x86-64";
+@@ -1757,15 +1918,17 @@
+   }
+ 
+   case llvm::Triple::sparc:
+-  case llvm::Triple::sparcel:
+   case llvm::Triple::sparcv9:
++    return sparc::getSparcTargetCPU(Args, T);
++
++  case llvm::Triple::sparcel:
+     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
+       return A->getValue();
+     return "";
+ 
+   case llvm::Triple::x86:
+   case llvm::Triple::x86_64:
+-    return getX86TargetCPU(Args, T);
++    return x86::getX86TargetCPU(Args, T);
+ 
+   case llvm::Triple::hexagon:
+     return "hexagon" +
+@@ -3084,7 +3247,7 @@
+ 
+ // Fallback to user id.
+ #ifdef LLVM_ON_UNIX
+-  std::string UID = llvm::utostr(getuid());
++  std::string UID = std::to_string(static_cast<unsigned int>(getuid()));
+ #else
+   // FIXME: Windows seems to have an 'SID' that might work.
+   std::string UID = "9999";
+@@ -3263,10 +3426,12 @@
+   // ToolChain.getTriple() and Triple?
+   bool PIE = ToolChain.isPIEDefault();
+   bool PIC = PIE || ToolChain.isPICDefault();
++
+   // The Darwin/MachO default to use PIC does not apply when using -static.
+   if (ToolChain.getTriple().isOSBinFormatMachO() &&
+       Args.hasArg(options::OPT_static))
+     PIE = PIC = false;
++
+   bool IsPICLevelTwo = PIC;
+ 
+   bool KernelOrKext =
+@@ -3320,6 +3485,24 @@
+     }
+   }
+ 
++  // Solaris-specific defaults for PIE
++  if (ToolChain.getTriple().getOS() == llvm::Triple::Solaris) {
++    switch (ToolChain.getTriple().getArch()) {
++    case llvm::Triple::x86:
++      IsPICLevelTwo = false; // "-fpie"
++      break;
++    case llvm::Triple::sparc:
++    case llvm::Triple::x86_64:
++    case llvm::Triple::sparcv9:
++      IsPICLevelTwo = true; // "-fPIE"
++      break;
++
++    default:
++      break;
++    }
++  }
++
++
+   // The last argument relating to either PIC or PIE wins, and no
+   // other argument is used. If the last argument is any flavor of the
+   // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
+@@ -3336,8 +3519,8 @@
+       if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
+           O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
+         PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
+-        PIC =
+-            PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
++        PIC = PIE || O.matches(options::OPT_fPIC) ||
++          O.matches(options::OPT_fpic);
+         IsPICLevelTwo =
+             O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
+       } else {
+@@ -3367,10 +3550,37 @@
+                        !Triple.isWatchOS()))
+     PIC = PIE = false;
+ 
++  if (ToolChain.getTriple().getOS() == llvm::Triple::Solaris) {
++    unsigned PICLevel = IsPICLevelTwo ? 2 : 1;
++    if (Arg *A = Args.getLastArg(options::OPT_shared)) {
++      PIC = true;
++      PIE = false;
++      return std::make_tuple(llvm::Reloc::PIC_, PICLevel, PIE);
++    } else if (PIE) {
++      PIC = PIE = true;
++      return std::make_tuple(llvm::Reloc::PIC_, PICLevel, PIE);
++    } else if (PIC) {
++      PIC = true;
++      PIE = IsPICLevelTwo;
++      return std::make_tuple(llvm::Reloc::PIC_, PICLevel, PIE);
++    } else if (Args.hasArg(options::OPT_static)) {
++      // Solaris doesn't to static relocations.
++      PIC = PIE = false;
++      return std::make_tuple(llvm::Reloc::DynamicNoPIC, PICLevel, PIE);
++    } else {
++      // This is a Solaris non-PIE executable.
++      // Solaris doesn't to static relocations.
++      PIC = PIE = false;
++      PICLevel = 0;
++      return std::make_tuple(llvm::Reloc::DynamicNoPIC, PICLevel, PIE);
++    }
++  }
++
+   if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
+     // This is a very special mode. It trumps the other modes, almost no one
+     // uses it, and it isn't even valid on any OS but Darwin.
+-    if (!ToolChain.getTriple().isOSDarwin())
++    if (!ToolChain.getTriple().isOSDarwin() &&
++        !ToolChain.getTriple().isOSSolaris())
+       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
+           << A->getSpelling() << ToolChain.getTriple().str();
+ 
+@@ -3404,18 +3614,6 @@
+   llvm_unreachable("Unknown Reloc::Model kind");
+ }
+ 
+-static void AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
+-                             ArgStringList &CmdArgs) {
+-  llvm::Reloc::Model RelocationModel;
+-  unsigned PICLevel;
+-  bool IsPIE;
+-  std::tie(RelocationModel, PICLevel, IsPIE) =
+-      ParsePICArgs(ToolChain, ToolChain.getTriple(), Args);
+-
+-  if (RelocationModel != llvm::Reloc::Static)
+-    CmdArgs.push_back("-KPIC");
+-}
+-
+ void Clang::ConstructJob(Compilation &C, const JobAction &JA,
+                          const InputInfo &Output, const InputInfoList &Inputs,
+                          const ArgList &Args, const char *LinkingOutput) const {
+@@ -3713,6 +3911,14 @@
+     CmdArgs.push_back(A->getValue());
+   }
+ 
++  if (Arg *A = Args.getLastArg(options::OPT_fabi_version_EQ)) {
++    StringRef V = A->getValue();
++    CmdArgs.push_back(Args.MakeArgString("-fabi-version=" + V));
++    A->claim();
++  } else {
++    CmdArgs.push_back(Args.MakeArgString("-fabi-version=4"));
++  }
++
+   if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
+                                options::OPT_freg_struct_return)) {
+     if (getToolChain().getArch() != llvm::Triple::x86) {
+@@ -4522,6 +4728,7 @@
+     // If -fmessage-length=N was not specified, determine whether this is a
+     // terminal and, if so, implicitly define -fmessage-length appropriately.
+     unsigned N = llvm::sys::Process::StandardErrColumns();
++    if (N == 0U) N = 72U;
+     CmdArgs.push_back(Args.MakeArgString(Twine(N)));
+   }
+ 
+@@ -4707,6 +4914,10 @@
+   if (Args.hasArg(options::OPT_mstack_alignment)) {
+     StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
+     CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
++  } else {
++    if ((getToolChain().getArch() == llvm::Triple::sparc) ||
++        (getToolChain().getArch() == llvm::Triple::sparcv9))
++      CmdArgs.push_back("-mstack-alignment=16");
+   }
+ 
+   if (Args.hasArg(options::OPT_mstack_probe_size)) {
+@@ -4963,16 +5174,16 @@
+   }
+ 
+   // -fuse-cxa-atexit is default.
+-  if (!Args.hasFlag(
++  if ((!Args.hasFlag(
+           options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
+           !IsWindowsCygnus && !IsWindowsGNU &&
+-              getToolChain().getTriple().getOS() != llvm::Triple::Solaris &&
+               getToolChain().getArch() != llvm::Triple::hexagon &&
+               getToolChain().getArch() != llvm::Triple::xcore &&
+               ((getToolChain().getTriple().getVendor() !=
+                 llvm::Triple::MipsTechnologies) ||
+                getToolChain().getTriple().hasEnvironment())) ||
+-      KernelOrKext)
++      KernelOrKext) &&
++      !getToolChain().getTriple().getOS() == llvm::Triple::Solaris)
+     CmdArgs.push_back("-fno-use-cxa-atexit");
+ 
+   // -fms-extensions=0 is default.
+@@ -5425,8 +5636,10 @@
+   // nice to enable this when doing a crashdump for modules as well.
+   if (Args.hasFlag(options::OPT_frewrite_includes,
+                    options::OPT_fno_rewrite_includes, false) ||
+-      (C.isForDiagnostics() && !HaveModules))
++      (C.isForDiagnostics() && !HaveModules)) {
++    if (getToolChain().getTriple().getOS() != llvm::Triple::Solaris)
+     CmdArgs.push_back("-frewrite-includes");
++  }
+ 
+   // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
+   if (Arg *A = Args.getLastArg(options::OPT_traditional,
+@@ -6155,7 +6368,10 @@
+     CmdArgs.push_back("-fsyntax-only");
+   }
+ 
+-  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
++  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
++                       options::OPT_Xassembler);
++  Args.ClaimAllArgs(options::OPT_Wa_COMMA);
++  Args.ClaimAllArgs(options::OPT_Xassembler);
+ 
+   // Only pass -x if gcc will understand it; otherwise hope gcc
+   // understands the suffix correctly. The main use case this would go
+@@ -7383,44 +7599,362 @@
+   claimNoWarnArgs(Args);
+   ArgStringList CmdArgs;
+ 
+-  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
++  const toolchains::Solaris &TC =
++    static_cast<const toolchains::Solaris&>(getToolChain());
++
++  if (!TC.isValid()) {
++    llvm::errs() << "Invalid GCC installation!\n";
++    return;
++  }
+ 
++  std::string EffectiveTriple = TC.ComputeLLVMTriple(Args, types::ID(0));
++  llvm::Triple ET(EffectiveTriple);
++
++  const Driver &D = TC.getDriver();
++  llvm::Triple::ArchType Arch = ET.getArch();
++  StringRef AS = TC.getAssembler();
++  bool m32 = !!Args.getLastArg(options::OPT_m32);
++
++  std::string march;
++  std::string mtune;
++  std::string mcpu;
++
++  if (Arg *A = Args.getLastArg(options::OPT_march_EQ))
++    march = A->getValue();
++  else
++    march = TC.getMArch();
++
++  if (Arg *A = Args.getLastArg(options::OPT_mtune_EQ))
++    mtune = A->getValue();
++  else
++    mtune = TC.getMTune();
++
++  if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
++    mcpu = A->getValue();
++  else
++    mcpu = TC.getMCpu();
++
++  if (Args.hasArg(options::OPT_v))
++    CmdArgs.push_back("-V");
++
++  switch (Arch) {
++  case llvm::Triple::x86:
++  case llvm::Triple::x86_64:
++    if (m32)
++      CmdArgs.push_back("--32");
++    else
++      CmdArgs.push_back("--64");
++    break;
++  case llvm::Triple::sparc:
++  case llvm::Triple::sparcv9:
++    if (m32) {
++      CmdArgs.push_back("-32");
++      if (march.empty())
++        march="v8plusa";
++      if (mcpu.empty())
++        mcpu="v8plusa";
++    } else {
++      CmdArgs.push_back("-64");
++      if (march.empty())
++        march="v9a";
++      if (mcpu.empty())
++        mcpu="v9a";
++    }
++    break;
++  default:
++    D.Diag(diag::err_target_unsupported_arch) << ET.getArchName()
++      << ET.getTriple();
++    break;
++  }
++
++  std::string xarch;
++
++  switch (Arch) {
++  case llvm::Triple::sparc:
++  case llvm::Triple::sparcv9:
++    xarch = "-xarch=";
++    xarch += clang::driver::tools::sparc::getSparcTargetCPU(Args, ET);
++    CmdArgs.push_back(Args.MakeArgString(xarch.c_str()));
++    AddAssemblerKPIC(TC, Args, CmdArgs);
++    CmdArgs.push_back("-no-undeclared-regs");
++    if (Args.hasArg(options::OPT_mstrict_align))
++      CmdArgs.push_back("--enforce-aligned-data");
++    break;
++  case llvm::Triple::x86:
++  case llvm::Triple::x86_64:
++    xarch = "-march=";
++    xarch += clang::driver::tools::x86::getX86TargetCPU(Args, ET);
++    CmdArgs.push_back(Args.MakeArgString(xarch.c_str()));
++    break;
++  default:
++    D.Diag(diag::err_target_unsupported_arch) << ET.getArchName()
++      << ET.getTriple();
++    break;
++  }
++
++  if (Args.hasArg(options::OPT_g_Flag) || Args.hasArg(options::OPT_g0) ||
++      Args.hasArg(options::OPT_g1) || Args.hasArg(options::OPT_g2) ||
++      Args.hasArg(options::OPT_g3))
++    CmdArgs.push_back("--gen-debug");
++
++  if (Output.isFilename()) {
+   CmdArgs.push_back("-o");
+   CmdArgs.push_back(Output.getFilename());
++  } else {
++    D.Diag(diag::err_drv_invalid_gcc_output_type) << "<unspecified>";
++    CmdArgs.push_back("-fsyntax-only");
++  }
+ 
+-  for (const auto &II : Inputs)
++  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
++                       options::OPT_Xassembler);
++
++  for (const auto &II : Inputs) {
++    if (II.isFilename())
+     CmdArgs.push_back(II.getFilename());
++    else
++      II.getInputArg().render(Args, CmdArgs);
++  }
+ 
+-  const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
++  const char *Exec = AS.data();
+   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
+ }
+ 
++void
++solaris::Assembler::RenderExtraToolArgs(const JobAction &JA,
++                                        llvm::opt::ArgStringList &CmdArgs) const {
++  // FIXME: IMPLEMENT
++}
++
++bool solaris::Linker::checkGnuLd(StringRef Path) const {
++  if (Path.empty()) return false;
++
++  char Buf[_POSIX_PATH_MAX+1];
++  std::string CMD = Path.str();
++  CMD += " -v 2>&1";
++
++  std::FILE *FP = ::popen(CMD.c_str(), "r");
++  if (!FP) return false;
++
++  (void) std::memset(Buf, 0, sizeof(Buf));
++  (void) std::fgets(Buf, _POSIX_PATH_MAX, FP);
++  ::pclose(FP);
++
++  return !!std::strstr(Buf, "GNU");
++}
++
+ void solaris::Linker::ConstructJob(Compilation &C, const JobAction &JA,
+                                    const InputInfo &Output,
+                                    const InputInfoList &Inputs,
+                                    const ArgList &Args,
+                                    const char *LinkingOutput) const {
++  const toolchains::Solaris& TC =
++    static_cast<const toolchains::Solaris&>(getToolChain());
++
++  if (!TC.isValid()) {
++    llvm::errs() << "Invalid GCC installation!\n";
++    return;
++  }
++
++  llvm::Triple TT = TC.getTriple();
++  std::string EffectiveTriple = TC.ComputeLLVMTriple(Args, types::ID(0));
++  llvm::Triple ET(EffectiveTriple);
++
++  const Driver &D = TC.getDriver();
++  llvm::Triple::ArchType Arch = TT.getArch();
++  bool m32 = !!Args.getLastArg(options::OPT_m32);
++
++  StringRef LD = TC.getLinker();
++  bool UseGnuLd = checkGnuLd(LD);
++
++  std::string GCCLibPath;
++  std::string YPPath;
++  GCCLibPath += "/lib/gcc/";
++  std::string LibPath = "/usr/lib/";
++  std::string ShortLibPath = "/lib/";
++  std::string ClangLibPath;
++  const char* moption;
++  std::string gldm;
++
++  if (UseGnuLd) {
++    switch (Arch) {
++    case llvm::Triple::x86:
++      if (m32)
++        gldm = "elf_i386_sol2";
++      else
++        gldm = "elf_x86_64_sol2";
++      break;
++    case llvm::Triple::x86_64:
++      if (m32)
++        gldm = "elf_i386_sol2";
++      else
++        gldm = "elf_x86_64_sol2";
++      break;
++    case llvm::Triple::sparc:
++      if (m32)
++        gldm = "elf32_sparc_sol2";
++      else
++        gldm = "elf64_sparc_sol2";
++      break;
++    case llvm::Triple::sparcv9:
++      if (m32)
++        gldm = "elf32_sparc_sol2";
++      else
++        gldm = "elf64_sparc_sol2";
++      break;
++    default:
++      break;
++    }
++  }
++
++  switch (Arch) {
++  case llvm::Triple::x86:
++    if (m32) {
++      GCCLibPath = TC.getGCCInternalLibDir().str();
++      GCCLibPath += "/";
++      moption = "-32";
++      YPPath = "/lib:/usr/lib";
++      ClangLibPath = "/usr/lib/clang/";
++    } else {
++      GCCLibPath = TC.getGCCInternalMultiLibDir().str();
++      GCCLibPath += "/";
++      LibPath += "amd64/";
++      ShortLibPath += "amd64/";
++      moption = "-64";
++      YPPath = "/lib/amd64:/usr/lib/amd64";
++      ClangLibPath = "/usr/lib/amd64/clang/";
++    }
++    break;
++  case llvm::Triple::sparc:
++    if (m32) {
++      GCCLibPath = TC.getGCCInternalLibDir().str();
++      GCCLibPath += "/";
++      moption = "-32";
++      YPPath = "/lib:/usr/lib";
++      ClangLibPath = "/usr/lib/clang/";
++    } else {
++      GCCLibPath = TC.getGCCInternalMultiLibDir().str();
++      GCCLibPath += "/";
++      LibPath += "sparcv9/";
++      ShortLibPath += "sparcv9/";
++      moption = "-64";
++      YPPath = "/lib/sparcv9:/usr/lib/sparcv9";
++      ClangLibPath = "/usr/lib/sparcv9/clang/";
++    }
++    break;
++  case llvm::Triple::x86_64:
++    if (m32) {
++      GCCLibPath = TC.getGCCInternalMultiLibDir().str();
++      GCCLibPath += "/";
++      moption = "-32";
++      YPPath = "/lib:/usr/lib";
++      ClangLibPath = "/usr/lib/clang/";
++    } else {
++      GCCLibPath = TC.getGCCInternalLibDir().str();
++      GCCLibPath += "/";
++    LibPath += "amd64/";
++      ShortLibPath += "amd64/";
++      moption = "-64";
++      YPPath = "/lib/amd64:/usr/lib/amd64";
++      ClangLibPath = "/usr/lib/amd64/clang/";
++    }
++    break;
++  case llvm::Triple::sparcv9:
++    if (m32) {
++      GCCLibPath = TC.getGCCInternalMultiLibDir().str();
++      GCCLibPath += "/";
++      moption = "-32";
++      YPPath = "/lib:/usr/lib";
++      ClangLibPath = "/usr/lib/clang/";
++    } else {
++      GCCLibPath = TC.getGCCInternalLibDir().str();
++      GCCLibPath += "/";
++      LibPath += "sparcv9/";
++      ShortLibPath += "sparcv9/";
++      moption = "-64";
++      YPPath = "/lib/sparcv9:/usr/lib/sparcv9";
++      ClangLibPath = "/usr/lib/sparcv9/clang/";
++    }
++    break;
++  default:
++    D.Diag(diag::err_target_unsupported_arch) << ET.getArchName()
++      << ET.getTriple();
++    break;
++  }
++
+   ArgStringList CmdArgs;
+ 
+-  // Demangle C++ names in errors
+-  CmdArgs.push_back("-C");
++  // THe -m flag to GNU ld is positional dependent.
++  // Do not change this ordering of options for the GNU ld.
++  if (!gldm.empty()) {
++    CmdArgs.push_back(Args.MakeArgString("-m"));
++    CmdArgs.push_back(Args.MakeArgString(gldm.c_str()));
++  }
+ 
+-  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
+-    CmdArgs.push_back("-e");
+-    CmdArgs.push_back("_start");
++  if (UseGnuLd) {
++    if (Args.hasArg(options::OPT_v))
++      CmdArgs.push_back(Args.MakeArgString("-v"));
++    CmdArgs.push_back(Args.MakeArgString("--as-needed"));
++  } else {
++    if (D.CCCIsCXX())
++      CmdArgs.push_back(Args.MakeArgString("-zrelax=comdat"));
+   }
+ 
++  Arg *PIEArg = Args.getLastArg(options::OPT_fPIE, options::OPT_fpie);
++  if (PIEArg) {
++    if (PIEArg->getOption().matches(options::OPT_fPIE) ||
++        PIEArg->getOption().matches(options::OPT_fpie)) {
++      CmdArgs.push_back(Args.MakeArgString("-Qy"));
++
++      if (UseGnuLd) {
++        CmdArgs.push_back(Args.MakeArgString("--pic-executable"));
++      } else {
++        CmdArgs.push_back(Args.MakeArgString("-zdirect"));
++        CmdArgs.push_back(Args.MakeArgString("-ztextwarn"));
++        CmdArgs.push_back(Args.MakeArgString("-ztype=pie"));
++        CmdArgs.push_back(Args.MakeArgString("-zaslr=enable"));
++      }
++    }
++  }
++
++  // Silence 'argument not used during compilation: -g' warning.
++  Args.ClaimAllArgs(options::OPT_g_Group);
++
++  // Silence 'argument unused during compilation: -pthread' warning.
++  Args.ClaimAllArgs(options::OPT_pthread);
++
++  // Language options
++  Args.ClaimAllArgs(options::OPT_emit_llvm);
++  Args.ClaimAllArgs(options::OPT_w);
++
++  if (Args.hasArg(options::OPT_s))
++    CmdArgs.push_back("-s");
++
++  const std::vector<std::string> &ExtraOpts = TC.getExtraOpts();
++
++  // Handle extra options
++  if (ExtraOpts.size()) {
++    for (std::vector<std::string>::const_iterator I = ExtraOpts.begin(),
++         E = ExtraOpts.end(); I != E; ++I)
++      CmdArgs.push_back((*I).c_str());
++  }
++
++  // Demangle C++ names
++  if (UseGnuLd)
++    CmdArgs.push_back("--demangle");
++  else
++    CmdArgs.push_back("-C");
++
+   if (Args.hasArg(options::OPT_static)) {
+     CmdArgs.push_back("-Bstatic");
+     CmdArgs.push_back("-dn");
+   } else {
+     CmdArgs.push_back("-Bdynamic");
++    CmdArgs.push_back("-dy");
+     if (Args.hasArg(options::OPT_shared)) {
+       CmdArgs.push_back("-shared");
+     } else {
+       CmdArgs.push_back("--dynamic-linker");
+-      CmdArgs.push_back(
+-          Args.MakeArgString(getToolChain().GetFilePath("ld.so.1")));
++      CmdArgs.push_back(Args.MakeArgString(LibPath + "ld.so.1"));
+     }
+   }
+ 
+@@ -7431,48 +7965,264 @@
+     assert(Output.isNothing() && "Invalid output.");
+   }
+ 
+-  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
+-    if (!Args.hasArg(options::OPT_shared))
+-      CmdArgs.push_back(
+-          Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
++  const char* Values = "values-Xa.o";
++  const char* Xpg = "values-xpg4.o";
+ 
+-    CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
+-    CmdArgs.push_back(
+-        Args.MakeArgString(getToolChain().GetFilePath("values-Xa.o")));
+-    CmdArgs.push_back(
+-        Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
++  Arg *STDArg = Args.getLastArg(options::OPT_std_EQ);
++  if (STDArg) {
++    if (STDArg->getOption().matches(options::OPT_std_EQ)) {
++      std::string Lang = STDArg->getValue();
++      if ((Lang == "c99") || (Lang == "c11") ||
++          (Lang == "c++11") || (Lang == "c++14")) {
++        Values = "values-Xc.o";
++        Xpg = "values-xpg6.o";
++      }
++    }
+   }
+ 
+-  getToolChain().AddFilePathLibArgs(Args, CmdArgs);
++  if (UseGnuLd) {
++    if (LD == "/usr/gnu/bin/ld.gold") {
++      if (Args.hasArg(options::OPT_O))
++        Args.AddAllArgs(CmdArgs, options::OPT_O);
++    } else
++      CmdArgs.push_back(Args.MakeArgString("-O"));
++  }
+ 
+-  Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
+-                            options::OPT_e, options::OPT_r});
++  if (Args.hasArg(options::OPT_v))
++    CmdArgs.push_back(Args.MakeArgString(StringRef("-V")));
+ 
+-  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
++  CmdArgs.push_back(Args.MakeArgString(StringRef("-Qy")));
+ 
+-  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
+-    if (getToolChain().getDriver().CCCIsCXX())
+-      getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
+-    CmdArgs.push_back("-lgcc_s");
+-    CmdArgs.push_back("-lc");
++  if (LD == "/usr/bin/ld") {
++    CmdArgs.push_back(Args.MakeArgString(StringRef("-Y")));
++    CmdArgs.push_back(Args.MakeArgString(StringRef("P," + YPPath)));
++  } else {
++    CmdArgs.push_back(Args.MakeArgString(StringRef("-Y")));
++    CmdArgs.push_back(Args.MakeArgString(StringRef(YPPath)));
++  }
++
++  CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
++
++  std::string P = GCCLibPath;
++  P += "../../..";
++  CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + P));
++
++  std::string crt1o;
++  bool S12OrHigher = false;
++
++  // We're not backporting this to S10. Until we do, that is.
++  if (EffectiveTriple.find("solaris2.11") == std::string::npos)
++    S12OrHigher = true;
++
++  if (!Args.hasArg(options::OPT_nostdlib) &&
++      !Args.hasArg(options::OPT_nostartfiles)) {
+     if (!Args.hasArg(options::OPT_shared)) {
+-      CmdArgs.push_back("-lgcc");
++      switch (Arch) {
++      case llvm::Triple::sparc:
++      case llvm::Triple::sparcv9:
++        if (S12OrHigher)
++          crt1o = LibPath;
++        else
++          crt1o = GCCLibPath;
++      case llvm::Triple::x86:
++      case llvm::Triple::x86_64:
++        crt1o = LibPath;
++        break;
++      default:
++        D.Diag(diag::err_target_unsupported_arch) << ET.getArchName()
++          << ET.getTriple();
++        break;
++      }
++
++      crt1o += "/crt1.o";
++
++      CmdArgs.push_back(Args.MakeArgString(crt1o.c_str()));
++      CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
++      CmdArgs.push_back(Args.MakeArgString(LibPath + Values));
++      CmdArgs.push_back(Args.MakeArgString(LibPath + Xpg));
++      CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + GCCLibPath));
++      CmdArgs.push_back(Args.MakeArgString("-L" + P));
++      CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
++    } else {
++      CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
++      CmdArgs.push_back(Args.MakeArgString(LibPath + Values));
++      CmdArgs.push_back(Args.MakeArgString(LibPath + Xpg));
++      CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + GCCLibPath));
++      CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + P));
++      CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
++    }
++  } else if (Args.hasArg(options::OPT_nostdlib) &&
++             !Args.hasArg(options::OPT_nostartfiles)) {
++    if (Args.hasArg(options::OPT_shared)) {
++      CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
++      CmdArgs.push_back(Args.MakeArgString(LibPath + Values));
++      CmdArgs.push_back(Args.MakeArgString(LibPath + Xpg));
++      CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + GCCLibPath));
++      CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + P));
++      CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
++    } else {
++      CmdArgs.push_back(Args.MakeArgString(crt1o.c_str()));
++      CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
++      CmdArgs.push_back(Args.MakeArgString(LibPath + Values));
++      CmdArgs.push_back(Args.MakeArgString(LibPath + Xpg));
++      CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + GCCLibPath));
++      CmdArgs.push_back(Args.MakeArgString("-L" + P));
++    }
++  } else if (!Args.hasArg(options::OPT_nostdlib) &&
++             Args.hasArg(options::OPT_nostartfiles)) {
++    if (Args.hasArg(options::OPT_shared)) {
++      CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtend.o"));
++    }
++  }
++
++  // Itanium C++ ABI.
++  std::string CXAFinalize;
++  bool HasSystemCXAFinalize = !S12OrHigher;
++
++  if (!Args.hasArg(options::OPT_shared)) {
++    if (PIEArg) {
++      if (PIEArg->getOption().matches(options::OPT_fPIE) ||
++          PIEArg->getOption().matches(options::OPT_fpie)) {
++        CXAFinalize = ClangLibPath + "cxa_finalize_pic.o";
++      }
++    } else {
++      CXAFinalize = ClangLibPath + "cxa_finalize.o";
++    }
++
++    HasSystemCXAFinalize = llvm::sys::fs::exists(CXAFinalize.c_str());
++
++    if (D.CCCIsCXX() && HasSystemCXAFinalize)
++      CmdArgs.push_back(Args.MakeArgString(CXAFinalize.c_str()));
++  }
++
++  CmdArgs.push_back(Args.MakeArgString(StringRef("-L" + GCCLibPath)));
++  CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
++  CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + ShortLibPath));
++
++  Args.AddAllArgs(CmdArgs, options::OPT_L);
++  const ToolChain::path_list Paths = TC.getFilePaths();
++  for (ToolChain::path_list::const_iterator B = Paths.begin(), E = Paths.end();
++       B != E; ++B) {
++    CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + *B));
++
++    // Itanium C++ ABI.
++    if (!Args.hasArg(options::OPT_shared)) {
++      if (D.CCCIsCXX() && !HasSystemCXAFinalize) {
++        if (PIEArg) {
++          if (PIEArg->getOption().matches(options::OPT_fPIE) ||
++              PIEArg->getOption().matches(options::OPT_fpie)) {
++            CXAFinalize = *B + "/cxa_finalize_pic.o";
++          }
++        } else {
++          CXAFinalize = *B + "/cxa_finalize.o";
++        }
++
++        if (llvm::sys::fs::exists(CXAFinalize.c_str()))
++          CmdArgs.push_back(Args.MakeArgString(CXAFinalize.c_str()));
++      }
++    }
++  }
++
++  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
++  Args.AddAllArgs(CmdArgs, options::OPT_e);
++  Args.AddAllArgs(CmdArgs, options::OPT_s);
++  Args.AddAllArgs(CmdArgs, options::OPT_t);
++  Args.AddAllArgs(CmdArgs, options::OPT_r);
++
++  std::vector<std::string>  zoptions = Args.getAllArgValues(options::OPT_z);
++  std::string zoption;
++
++  for (std::vector<std::string>::const_iterator B = zoptions.begin(),
++       E = zoptions.end(); B != E; ++B) {
++    zoption = "-z";
++    zoption += *B;
++    CmdArgs.push_back(Args.MakeArgString(StringRef(zoption)));
++  }
++
++  if (!Args.hasArg(options::OPT_mimpure_text) &&
++      !Args.hasArg(options::OPT_fpie) &&
++      !Args.hasArg(options::OPT_fPIE))
++    CmdArgs.push_back(Args.MakeArgString(StringRef("-ztext")));
++
++  // Itanium C++ ABI.
++  if (D.CCCIsCXX()) {
++    if (!Args.hasArg(options::OPT_shared)) {
++      if (HasSystemCXAFinalize) {
++        const char* zfiniarray = "-zfiniarray=__cxa_finalize";
++        CmdArgs.push_back(Args.MakeArgString(zfiniarray));
++      }
++    }
++  }
++
++  if (LD == "/usr/gnu/bin/ld.gold") {
++    CmdArgs.push_back("-plugin");
++    std::string Plugin = D.Dir + "/../lib/LLVMgold.so";
++    CmdArgs.push_back(Args.MakeArgString(Plugin));
++  }
++
++  if (!UseGnuLd) {
++    CmdArgs.push_back(moption);
++  }
++
++  if (Arg *A = Args.getLastArg(options::OPT_rpath)) {
++    StringRef V = A->getValue();
++    if (UseGnuLd) {
++      CmdArgs.push_back(Args.MakeArgString("-rpath"));
++      CmdArgs.push_back(Args.MakeArgString(V));
++    } else {
++      CmdArgs.push_back(Args.MakeArgString("-R"));
++      CmdArgs.push_back(Args.MakeArgString(V));
++    }
++  }
++
++  AddLinkerInputs(TC, Inputs, Args, CmdArgs);
++  AddLibgcc(D, CmdArgs, Args, LD.str());
++
++  if (!Args.hasArg(options::OPT_nostdlib) &&
++      !Args.hasArg(options::OPT_nodefaultlibs)) {
++    addOpenMPRuntime(CmdArgs, TC, Args);
++
++    if (D.CCCIsCXX())
++      TC.AddCXXStdlibLibArgs(Args, CmdArgs);
++
++    CmdArgs.push_back("-lc");
+       CmdArgs.push_back("-lm");
++    CmdArgs.push_back("-lgcc_s");
++
++    if (Args.hasArg(options::OPT_static)) {
++      CmdArgs.push_back("-lgcc");
++      CmdArgs.push_back("-lgcc_eh");
+     }
++  } else if (Args.hasArg(options::OPT_nostdlib) &&
++             (!Args.hasArg(options::OPT_nodefaultlibs))) {
++    CmdArgs.push_back("-lgcc_s");
++
++    if (Args.hasArg(options::OPT_static))
++      CmdArgs.push_back("-lgcc_eh");
+   }
+ 
+-  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
+-    CmdArgs.push_back(
+-        Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
++  if (!Args.hasArg(options::OPT_nostdlib) &&
++      !Args.hasArg(options::OPT_nostartfiles)) {
++    CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtend.o"));
+   }
+-  CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
+ 
+-  getToolChain().addProfileRTLibs(Args, CmdArgs);
++  CmdArgs.push_back(Args.MakeArgString(LibPath + "crtn.o"));
+ 
+-  const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
++  TC.addProfileRTLibs(Args, CmdArgs);
++
++  Args.ClaimAllArgs(options::OPT_Wl_COMMA);
++  Args.ClaimAllArgs(options::OPT_Xlinker);
++
++  const char *Exec = LD.data();
+   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
+ }
+ 
++void
++solaris::Linker::RenderExtraToolArgs(const JobAction &JA,
++                                     llvm::opt::ArgStringList &CmdArgs) const {
++  // FIXME: IMPLEMENT
++}
++
+ void openbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
+                                       const InputInfo &Output,
+                                       const InputInfoList &Inputs,
+@@ -8623,6 +9373,41 @@
+     CmdArgs.push_back("-ldl");
+ }
+ 
++static void AddLibgcc(const Driver &D, ArgStringList &CmdArgs,
++                      const ArgList &Args, const std::string& Exec) {
++  bool StaticLibgcc = Args.hasArg(options::OPT_static) ||
++    Args.hasArg(options::OPT_static_libgcc);
++  if (!D.CCCIsCXX())
++    CmdArgs.push_back("-lgcc");
++
++  if (StaticLibgcc) {
++    if (D.CCCIsCXX())
++      CmdArgs.push_back("-lgcc");
++  } else {
++    if ((!D.CCCIsCXX()) && ((Exec == "/usr/bin/gld") ||
++                            (Exec == "/usr/gnu/bin/ld") ||
++                            (Exec == "/usr/gnu/bin/ld.bfd") ||
++                            (Exec == "/usr/gnu/bin/ld.gold")))
++      CmdArgs.push_back("--as-needed");
++
++    CmdArgs.push_back("-lgcc_s");
++    if ((!D.CCCIsCXX()) && ((Exec == "/usr/bin/gld") ||
++                            (Exec == "/usr/gnu/bin/ld") ||
++                            (Exec == "/usr/gnu/bin/ld.bfd") ||
++                            (Exec == "/usr/gnu/bin/ld.gold")))
++      CmdArgs.push_back("--no-as-needed");
++  }
++
++  if (StaticLibgcc)
++    CmdArgs.push_back("-lgcc_eh");
++  else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
++    CmdArgs.push_back("-lgcc");
++
++  if (!StaticLibgcc)
++    CmdArgs.push_back("-ldl");
++}
++
++
+ static std::string getLinuxDynamicLinker(const ArgList &Args,
+                                          const toolchains::Linux &ToolChain) {
+   const llvm::Triple::ArchType Arch = ToolChain.getArch();
+###
+--- tools/clang/lib/Driver/Tools.h	2016-01-08 06:14:31.000000000 -0900
++++ tools/clang/lib/Driver/Tools.h	2016-07-04 11:21:03.646553390 -0800
+@@ -17,6 +17,8 @@
+ #include "clang/Frontend/CodeGenOptions.h"
+ #include "llvm/ADT/Triple.h"
+ #include "llvm/Option/Option.h"
++#include "llvm/Option/Arg.h"
++#include "llvm/Option/ArgList.h"
+ #include "llvm/Support/Compiler.h"
+ 
+ namespace clang {
+@@ -38,9 +40,10 @@
+ 
+ using llvm::opt::ArgStringList;
+ 
+-SmallString<128> getCompilerRT(const ToolChain &TC,
++SmallString<PATH_MAX> getCompilerRT(const ToolChain &TC,
+                                const llvm::opt::ArgList &Args,
+-                               StringRef Component, bool Shared = false);
++                                    StringRef Component,
++                                    bool Shared = false);
+ 
+ /// \brief Clang compiler tool.
+ class LLVM_LIBRARY_VISIBILITY Clang : public Tool {
+@@ -308,6 +311,16 @@
+ bool hasPPCAbiArg(const llvm::opt::ArgList &Args, const char *Value);
+ } // end namespace ppc
+ 
++namespace sparc {
++  const char *getSparcTargetCPU(const llvm::opt::ArgList &Args,
++                                const llvm::Triple &Triple);
++} // end namespace sparc
++
++namespace x86 {
++  const char *getX86TargetCPU(const llvm::opt::ArgList &Args,
++                              const llvm::Triple &Triple);
++} // end namespace x86
++
+ /// cloudabi -- Directly call GNU Binutils linker
+ namespace cloudabi {
+ class LLVM_LIBRARY_VISIBILITY Linker : public GnuTool {
+@@ -622,25 +635,32 @@
+ 
+ /// solaris -- Directly call Solaris assembler and linker
+ namespace solaris {
+-class LLVM_LIBRARY_VISIBILITY Assembler : public Tool {
++class LLVM_LIBRARY_VISIBILITY Assembler : public GnuTool {
+ public:
+   Assembler(const ToolChain &TC)
+-      : Tool("solaris::Assembler", "assembler", TC) {}
++    : GnuTool("solaris::Assembler", "assembler", TC) {}
+ 
+   bool hasIntegratedCPP() const override { return false; }
+ 
++  virtual void RenderExtraToolArgs(const JobAction &JA,
++                                   llvm::opt::ArgStringList &CmdArgs) const;
++
+   void ConstructJob(Compilation &C, const JobAction &JA,
+                     const InputInfo &Output, const InputInfoList &Inputs,
+                     const llvm::opt::ArgList &TCArgs,
+                     const char *LinkingOutput) const override;
+ };
+ 
+-class LLVM_LIBRARY_VISIBILITY Linker : public Tool {
++class LLVM_LIBRARY_VISIBILITY Linker : public GnuTool {
+ public:
+-  Linker(const ToolChain &TC) : Tool("solaris::Linker", "linker", TC) {}
++  Linker(const ToolChain &TC)
++    : GnuTool("solaris::Linker", "linker", TC) {}
+ 
+   bool hasIntegratedCPP() const override { return false; }
+   bool isLinkJob() const override { return true; }
++  bool checkGnuLd(StringRef Path) const;
++  virtual void RenderExtraToolArgs(const JobAction &JA,
++                                   llvm::opt::ArgStringList &CmdArgs) const;
+ 
+   void ConstructJob(Compilation &C, const JobAction &JA,
+                     const InputInfo &Output, const InputInfoList &Inputs,
+###
+--- tools/clang/lib/Driver/ToolChain.cpp	2015-11-25 16:02:07.000000000 -0900
++++ tools/clang/lib/Driver/ToolChain.cpp	2016-06-30 20:26:09.406980255 -0800
+@@ -408,6 +408,34 @@
+ 
+ std::string ToolChain::ComputeLLVMTriple(const ArgList &Args,
+                                          types::ID InputType) const {
++  llvm::Triple T = getTriple();
++  if (T.isOSSolaris()) {
++    if ((!Args.getLastArg(options::OPT_m32)) &&
++        (!Args.getLastArg(options::OPT_m64))) {
++      StringRef ArchName;
++
++      switch (T.getArch()) {
++      case llvm::Triple::x86_64:
++      case llvm::Triple::sparcv9:
++        return getTripleString();
++        break;
++      case llvm::Triple::sparc:
++        ArchName = "sparcv9";
++        T.setArchName(ArchName);
++        return T.getTriple();
++        break;
++      case llvm::Triple::x86:
++        ArchName = "x86_64";
++        T.setArchName(ArchName);
++        return T.getTriple();
++        break;
++      default:
++        llvm_unreachable("Unknonwn Solaris Target Triple!");
++        break;
++      }
++    }
++  }
++
+   switch (getTriple().getArch()) {
+   default:
+     return getTripleString();
+###
+
--- a/components/llvm/patches/013-llvm-alignments.patch	Thu Jul 28 16:15:45 2016 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,127 +0,0 @@
-# http://reviews.llvm.org/D10271
-# Backported to 3.6.2.
---- include/llvm/IR/DerivedTypes.h	2014-11-21 14:03:35.000000000 -0500
-+++ include/llvm/IR/DerivedTypes.h	2015-08-23 17:27:29.355504909 -0400
-@@ -140,7 +140,8 @@
-     return T->getTypeID() == FunctionTyID;
-   }
- };
--
-+static_assert(AlignOf<FunctionType>::Alignment >= AlignOf<Type *>::Alignment,
-+              "Insufficient alignment for objects appended to FunctionType");
- 
- /// CompositeType - Common super class of ArrayType, StructType, PointerType
- /// and VectorType.
---- include/llvm/IR/User.h	2014-10-15 16:39:05.000000000 -0400
-+++ include/llvm/IR/User.h	2015-08-23 17:27:29.365505148 -0400
-@@ -22,6 +22,7 @@
- #include "llvm/ADT/iterator.h"
- #include "llvm/ADT/iterator_range.h"
- #include "llvm/IR/Value.h"
-+#include "llvm/Support/AlignOf.h"
- #include "llvm/Support/ErrorHandling.h"
- 
- namespace llvm {
-@@ -172,6 +173,11 @@
-     return isa<Instruction>(V) || isa<Constant>(V);
-   }
- };
-+// Either Use objects, or a Use pointer can be prepended to User.
-+static_assert(AlignOf<Use>::Alignment >= AlignOf<User>::Alignment,
-+              "Insufficient alignment after objects prepended to User");
-+static_assert(AlignOf<Use *>::Alignment >= AlignOf<User>::Alignment,
-+              "Insufficient alignment after objects prepended to User");
- 
- template<> struct simplify_type<User::op_iterator> {
-   typedef Value* SimpleType;
---- include/llvm/Support/AlignOf.h	2014-01-08 22:28:55.000000000 -0500
-+++ include/llvm/Support/AlignOf.h	2015-08-23 17:27:29.365505148 -0400
-@@ -36,9 +36,18 @@
- ///  compile-time constant (e.g., for template instantiation).
- template <typename T>
- struct AlignOf {
-+#ifndef _MSC_VER
-+  // Avoid warnings from GCC like:
-+  //   comparison between 'enum llvm::AlignOf<X>::<anonymous>' and 'enum
-+  //   llvm::AlignOf<Y>::<anonymous>' [-Wenum-compare]
-+  // by using constexpr instead of enum.
-+  // (except on MSVC, since it doesn't support constexpr yet).
-+  static constexpr unsigned Alignment =
-+      static_cast<unsigned int>(sizeof(AlignmentCalcImpl<T>) - sizeof(T));
-+#else
-   enum { Alignment =
-          static_cast<unsigned int>(sizeof(AlignmentCalcImpl<T>) - sizeof(T)) };
--
-+#endif
-   enum { Alignment_GreaterEqual_2Bytes = Alignment >= 2 ? 1 : 0 };
-   enum { Alignment_GreaterEqual_4Bytes = Alignment >= 4 ? 1 : 0 };
-   enum { Alignment_GreaterEqual_8Bytes = Alignment >= 8 ? 1 : 0 };
-@@ -50,6 +59,10 @@
-   enum { Alignment_LessEqual_16Bytes = Alignment <= 16 ? 1 : 0 };
- };
- 
-+#ifndef _MSC_VER
-+template <typename T> constexpr unsigned AlignOf<T>::Alignment;
-+#endif
-+
- /// 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:
---- lib/IR/AttributeImpl.h	2014-08-13 12:26:38.000000000 -0400
-+++ lib/IR/AttributeImpl.h	2015-08-23 17:27:29.366505172 -0400
-@@ -180,6 +180,9 @@
-       AttrList[I].Profile(ID);
-   }
- };
-+static_assert(AlignOf<AttributeSetNode>::Alignment >=
-+                  AlignOf<Attribute>::Alignment,
-+              "Insufficient alignment for objects appended to AttributeSetNode");
- 
- //===----------------------------------------------------------------------===//
- /// \class
-@@ -188,9 +191,11 @@
- class AttributeSetImpl : public FoldingSetNode {
-   friend class AttributeSet;
- 
--  LLVMContext &Context;
--
-+public:
-   typedef std::pair<unsigned, AttributeSetNode*> IndexAttrPair;
-+
-+private:
-+  LLVMContext &Context;
-   unsigned NumAttrs; ///< Number of entries in this set.
- 
-   /// \brief Return a pointer to the IndexAttrPair for the specified slot.
-@@ -205,6 +210,7 @@
-   AttributeSetImpl(LLVMContext &C,
-                    ArrayRef<std::pair<unsigned, AttributeSetNode *> > Attrs)
-       : Context(C), NumAttrs(Attrs.size()) {
-+
- #ifndef NDEBUG
-     if (Attrs.size() >= 2) {
-       for (const std::pair<unsigned, AttributeSetNode *> *i = Attrs.begin() + 1,
-@@ -266,6 +272,9 @@
- 
-   void dump() const;
- };
-+static_assert(AlignOf<AttributeSetImpl>::Alignment >=
-+                  AlignOf<AttributeSetImpl::IndexAttrPair>::Alignment,
-+              "Insufficient alignment for objects appended to AttributeSetImpl");
- 
- } // end llvm namespace
- 
---- lib/IR/User.cpp	2015-08-23 17:27:29.366505172 -0400
-+++ lib/IR/User.cpp	2015-08-23 17:34:56.427494589 -0400
-@@ -40,6 +40,11 @@
- //===----------------------------------------------------------------------===//
- 
- Use *User::allocHungoffUses(unsigned N) const {
-+  static_assert(AlignOf<Use>::Alignment >= AlignOf<Use::UserRef>::Alignment,
-+                "Insufficient alignment for hung-off-uses objects");
-+  static_assert(AlignOf<Use::UserRef>::Alignment >=
-+                AlignOf<BasicBlock*>::Alignment,
-+                "Insufficient alignment for hung-off-uses objects");
-   // Allocate the array of Uses, followed by a pointer (with bottom bit set) to
-   // the User.
-   size_t size = N * sizeof(Use) + sizeof(Use::UserRef);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/013-solaris-clang-libclangFrontend.patch	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,126 @@
+# Solaris GCC Toolchain.
+# 3.9.X upstream.
+--- tools/clang/lib/Frontend/CompilerInvocation.cpp	2016-01-12 16:01:56.000000000 -0500
++++ tools/clang/lib/Frontend/CompilerInvocation.cpp	2016-05-08 23:19:20.574431774 -0400
+@@ -1718,6 +1718,7 @@
+   Opts.EmitAllDecls = Args.hasArg(OPT_femit_all_decls);
+   Opts.PackStruct = getLastArgIntValue(Args, OPT_fpack_struct_EQ, 0, Diags);
+   Opts.MaxTypeAlign = getLastArgIntValue(Args, OPT_fmax_type_align_EQ, 0, Diags);
++  Opts.GXXABIVersion = getLastArgIntValue(Args, OPT_fabi_version_EQ, 0, Diags);
+   Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
+   Opts.PIELevel = getLastArgIntValue(Args, OPT_pie_level, 0, Diags);
+   Opts.Static = Args.hasArg(OPT_static_define);
+--- tools/clang/lib/Frontend/InitHeaderSearch.cpp	2015-12-29 22:40:23.000000000 -0500
++++ tools/clang/lib/Frontend/InitHeaderSearch.cpp	2016-05-08 23:19:20.575431798 -0400
+@@ -118,7 +118,7 @@
+   // Add the path with sysroot prepended, if desired and this is a system header
+   // group.
+   if (HasSysroot) {
+-    SmallString<256> MappedPathStorage;
++    SmallString<PATH_MAX> MappedPathStorage;
+     StringRef MappedPathStr = Path.toStringRef(MappedPathStorage);
+     if (CanPrefixSysroot(MappedPathStr)) {
+       AddUnmappedPath(IncludeSysroot + Path, Group, isFramework);
+@@ -134,7 +134,7 @@
+   assert(!Path.isTriviallyEmpty() && "can't handle empty path here");
+ 
+   FileManager &FM = Headers.getFileMgr();
+-  SmallString<256> MappedPathStorage;
++  SmallString<PATH_MAX> MappedPathStorage;
+   StringRef MappedPathStr = Path.toStringRef(MappedPathStorage);
+ 
+   // Compute the DirectoryLookup type.
+@@ -183,12 +183,16 @@
+ 
+   // Add the multilib dirs
+   llvm::Triple::ArchType arch = triple.getArch();
+-  bool is64bit = arch == llvm::Triple::ppc64 || arch == llvm::Triple::x86_64;
++  bool is64bit = arch == llvm::Triple::ppc64 || arch == llvm::Triple::x86_64 ||
++    arch == llvm::Triple::sparcv9;
+   if (is64bit)
+     AddPath(Base + "/" + ArchDir + "/" + Dir64, CXXSystem, false);
+   else
+     AddPath(Base + "/" + ArchDir + "/" + Dir32, CXXSystem, false);
+ 
++  // Add GCC's "C" include dir
++  AddPath(Base + "/include", CXXSystem, false);
++
+   // Add the backward dir
+   AddPath(Base + "/backward", CXXSystem, false);
+ }
+@@ -442,6 +446,7 @@
+     break; // Everything else continues to use this routine's logic.
+ 
+   case llvm::Triple::Linux:
++  case llvm::Triple::Solaris:
+     return;
+ 
+   case llvm::Triple::Win32:
+@@ -463,7 +468,7 @@
+           // Remove clang from foo/lib/clang
+           StringRef Lib = llvm::sys::path::parent_path(NoVer);
+           // Remove lib from foo/lib
+-          SmallString<128> P = llvm::sys::path::parent_path(Lib);
++          SmallString<PATH_MAX> P = llvm::sys::path::parent_path(Lib);
+ 
+           // Get foo/include/c++/v1
+           llvm::sys::path::append(P, "include", "c++", "v1");
+--- tools/clang/lib/Frontend/InitPreprocessor.cpp	2015-11-17 17:28:55.000000000 -0500
++++ tools/clang/lib/Frontend/InitPreprocessor.cpp	2016-05-08 23:19:20.575431798 -0400
+@@ -484,17 +484,51 @@
+   Builder.defineMacro("__clang_patchlevel__", "0");
+ #endif
+   Builder.defineMacro("__clang_version__", 
+-                      "\"" CLANG_VERSION_STRING " "
+-                      + getClangFullRepositoryVersion() + "\"");
++                      "\"" CLANG_VERSION_STRING " " CLANG_VERSION_TAGGED_STRING "\"");
++
+ #undef TOSTR
+ #undef TOSTR2
+   if (!LangOpts.MSVCCompat) {
+     // Currently claim to be compatible with GCC 4.2.1-5621, but only if we're
+     // not compiling for MSVC compatibility
+-    Builder.defineMacro("__GNUC_MINOR__", "2");
+-    Builder.defineMacro("__GNUC_PATCHLEVEL__", "1");
++    if (TI.getTriple().getOS() == llvm::Triple::Solaris) {
++      Builder.defineMacro("__GNUC_MINOR__", "8");
++      Builder.defineMacro("__GNUC_PATCHLEVEL__", "0");
++    } else {
++      Builder.defineMacro("__GNUC_MINOR__", "2");
++      Builder.defineMacro("__GNUC_PATCHLEVEL__", "1");
++    }
++
+     Builder.defineMacro("__GNUC__", "4");
+-    Builder.defineMacro("__GXX_ABI_VERSION", "1002");
++
++    // GCC provides a number of C++ ABI Versions in:
++    // ${top_srcdir}/gcc/c-family/c-cppbuiltin.c
++    // Currently valid GXX ABI Versions are documented here:
++    // https://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Dialect-Options.html
++    // clang only supports a subset.
++    switch (LangOpts.GXXABIVersion) {
++    default:
++      Builder.defineMacro("__GXX_ABI_VERSION", "1002");
++      break;
++        case 4:
++      Builder.defineMacro("__GXX_ABI_VERSION", "1004");
++      break;
++        case 5:
++      Builder.defineMacro("__GXX_ABI_VERSION", "1005");
++      break;
++        case 6:
++      Builder.defineMacro("__GXX_ABI_VERSION", "1006");
++      break;
++        case 7:
++      Builder.defineMacro("__GXX_ABI_VERSION", "1007");
++      break;
++        case 8:
++      Builder.defineMacro("__GXX_ABI_VERSION", "1008");
++      break;
++        case 9:
++      Builder.defineMacro("__GXX_ABI_VERSION", "1009");
++      break;
++    }
+   }
+ 
+   // Define macros for the C11 / C++11 memory orderings
--- a/components/llvm/patches/014-clang-gcc-toolchain.patch	Thu Jul 28 16:15:45 2016 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,2323 +0,0 @@
-# Solaris GCC Toolchain discovery.
-# https://llvm.org/bugs/show_bug.cgi?id=24606
---- lib/Support/Host.cpp	2014-12-16 19:38:04.000000000 -0800
-+++ lib/Support/Host.cpp	2016-02-09 09:59:19.281147309 -0800
-@@ -39,6 +39,11 @@
- #include <mach/machine.h>
- #endif
- 
-+#if defined(sun) || defined(__sun) || defined(__sun__)
-+#include <cstring>
-+#include <kstat.h>
-+#endif
-+
- #define DEBUG_TYPE "host-detection"
- 
- //===----------------------------------------------------------------------===//
-@@ -674,6 +679,43 @@
-   
-   return "generic";
- }
-+#elif ((defined(sun) || defined(__sun) || defined(__sun__)) && \
-+       (defined(sparc) || defined(__sparc) || defined(__sparc__)))
-+StringRef sys::getHostCPUName() {
-+  kstat_ctl_t *KC = 0;
-+  kstat_t *KSP = 0;
-+  kstat_named_t *KNP = 0;
-+  static char Buffer[256];
-+  static bool Init = false;
-+  const char *Value;
-+
-+  if (!Init) {
-+    KC = kstat_open();
-+    if (KC) {
-+      KSP = kstat_lookup(KC, "cpu_info", -1, "cpu_info0");
-+      kstat_read(KC, KSP, NULL);
-+      KNP = reinterpret_cast<kstat_named_t*>(kstat_data_lookup(KSP, "brand"));
-+      Value = (const char *) KNP->value.str.addr.ptr;
-+      (void) std::sprintf(Buffer, "%s (", Value);
-+
-+      KNP =
-+        reinterpret_cast<kstat_named_t*>(kstat_data_lookup(KSP, "cpu_type"));
-+      Value = (const char*) KNP->value.c;
-+      (void) std::strcat(Buffer, Value);
-+      (void) std::strcat(Buffer, ") ");
-+
-+      KNP =
-+        reinterpret_cast<kstat_named_t*>(kstat_data_lookup(KSP,
-+                                                           "implementation"));
-+      Value = (const char*) KNP->value.str.addr.ptr;
-+      (void) std::strcat(Buffer, Value);
-+      Init = true;
-+      kstat_close(KC);
-+    }
-+  }
-+
-+  return Buffer;
-+}
- #else
- StringRef sys::getHostCPUName() {
-   return "generic";
---- tools/clang/include/clang/Driver/Options.td	Sat Jul 18 11:44:46 2015
-+++ tools/clang/include/clang/Driver/Options.td	Thu Aug 20 22:46:37 2015
-@@ -1129,6 +1129,11 @@
- def mthread_model : Separate<["-"], "mthread-model">, Group<m_Group>, Flags<[CC1Option]>,
-   HelpText<"The thread model to use, e.g. posix, single (posix by default)">;
- 
-+def mvis : Flag<["-"], "mvis">, Group<m_Group>;
-+def mvis2 : Flag<["-"], "mvis2">, Group<m_Group>;
-+def mvis3 : Flag<["-"], "mvis3">, Group<m_Group>;
-+def mimpure_text: Flag<["-"], "mimpure-text">, Group<m_Group>;
-+
- def mmmx : Flag<["-"], "mmmx">, Group<m_x86_Features_Group>;
- def mno_3dnowa : Flag<["-"], "mno-3dnowa">, Group<m_x86_Features_Group>;
- def mno_3dnow : Flag<["-"], "mno-3dnow">, Group<m_x86_Features_Group>;
-@@ -1690,6 +1695,7 @@
- defm profile_use : BooleanFFlag<"profile-use">, Group<clang_ignored_gcc_optimization_f_Group>;
- def fprofile_use_EQ : Joined<["-"], "fprofile-use=">, Group<clang_ignored_gcc_optimization_f_Group>;
- def fuse_ld_EQ : Joined<["-"], "fuse-ld=">, Group<f_Group>;
-+def fuse_as_EQ : Joined<["-"], "fuse-as=">, Group<f_Group>;
- 
- defm align_functions : BooleanFFlag<"align-functions">, Group<clang_ignored_gcc_optimization_f_Group>;
- def falign_functions_EQ : Joined<["-"], "falign-functions=">, Group<clang_ignored_gcc_optimization_f_Group>;
---- tools/clang/lib/Frontend/InitHeaderSearch.cpp	Thu Dec  4 16:22:48 2014
-+++ tools/clang/lib/Frontend/InitHeaderSearch.cpp	Fri Aug 21 23:23:27 2015
-@@ -122,7 +122,7 @@
-   // Add the path with sysroot prepended, if desired and this is a system header
-   // group.
-   if (HasSysroot) {
--    SmallString<256> MappedPathStorage;
-+    SmallString<PATH_MAX> MappedPathStorage;
-     StringRef MappedPathStr = Path.toStringRef(MappedPathStorage);
-     if (CanPrefixSysroot(MappedPathStr)) {
-       AddUnmappedPath(IncludeSysroot + Path, Group, isFramework);
-@@ -138,7 +138,7 @@
-   assert(!Path.isTriviallyEmpty() && "can't handle empty path here");
- 
-   FileManager &FM = Headers.getFileMgr();
--  SmallString<256> MappedPathStorage;
-+  SmallString<PATH_MAX> MappedPathStorage;
-   StringRef MappedPathStr = Path.toStringRef(MappedPathStorage);
- 
-   // Compute the DirectoryLookup type.
-@@ -187,12 +187,16 @@
- 
-   // Add the multilib dirs
-   llvm::Triple::ArchType arch = triple.getArch();
--  bool is64bit = arch == llvm::Triple::ppc64 || arch == llvm::Triple::x86_64;
-+  bool is64bit = arch == llvm::Triple::ppc64 || arch == llvm::Triple::x86_64 ||
-+    arch == llvm::Triple::sparcv9;
-   if (is64bit)
-     AddPath(Base + "/" + ArchDir + "/" + Dir64, CXXSystem, false);
-   else
-     AddPath(Base + "/" + ArchDir + "/" + Dir32, CXXSystem, false);
- 
-+  // Add GCC's "C" include dir
-+  AddPath(Base + "/include", CXXSystem, false);
-+
-   // Add the backward dir
-   AddPath(Base + "/backward", CXXSystem, false);
- }
-@@ -442,8 +446,7 @@
-                                 "", "", "", triple);
-     break;
-   case llvm::Triple::Solaris:
--    AddGnuCPlusPlusIncludePaths("/usr/gcc/4.5/include/c++/4.5.2/",
--                                "i386-pc-solaris2.11", "", "", triple);
-+    // All of this is handled in the driver.
-     break;
-   default:
-     break;
-@@ -462,6 +465,7 @@
-     break; // Everything else continues to use this routine's logic.
- 
-   case llvm::Triple::Linux:
-+  case llvm::Triple::Solaris:
-     return;
- 
-   case llvm::Triple::Win32:
-@@ -484,7 +488,7 @@
-           // Remove clang from foo/lib/clang
-           StringRef Lib = llvm::sys::path::parent_path(NoVer);
-           // Remove lib from foo/lib
--          SmallString<128> P = llvm::sys::path::parent_path(Lib);
-+          SmallString<PATH_MAX> P = llvm::sys::path::parent_path(Lib);
- 
-           // Get foo/include/c++/v1
-           llvm::sys::path::append(P, "include", "c++", "v1");
-@@ -491,10 +495,6 @@
-           AddUnmappedPath(P.str(), CXXSystem, false);
-         }
-       }
--      // On Solaris, include the support directory for things like xlocale and
--      // fudged system headers.
--      if (triple.getOS() == llvm::Triple::Solaris) 
--        AddPath("/usr/include/c++/v1/support/solaris", CXXSystem, false);
-       
-       AddPath("/usr/include/c++/v1", CXXSystem, false);
-     } else {
---- tools/clang/lib/Driver/Tools.h	Wed Jan 28 15:52:21 2015
-+++ tools/clang/lib/Driver/Tools.h	Thu Aug 20 22:46:37 2015
-@@ -529,6 +529,9 @@
- 
-     bool hasIntegratedCPP() const override { return false; }
- 
-+    void RenderExtraToolArgs(const JobAction &JA,
-+                             ArgStringList &CmdArgs) const;
-+
-     void ConstructJob(Compilation &C, const JobAction &JA,
-                       const InputInfo &Output, const InputInfoList &Inputs,
-                       const llvm::opt::ArgList &TCArgs,
-@@ -541,6 +544,9 @@
-     bool hasIntegratedCPP() const override { return false; }
-     bool isLinkJob() const override { return true; }
- 
-+    void RenderExtraToolArgs(const JobAction &JA,
-+                             ArgStringList &CmdArgs) const;
-+
-     void ConstructJob(Compilation &C, const JobAction &JA,
-                       const InputInfo &Output, const InputInfoList &Inputs,
-                       const llvm::opt::ArgList &TCArgs,
---- tools/clang/lib/Driver/Tools.cpp	Sat Jul 18 11:44:46 2015
-+++ tools/clang/lib/Driver/Tools.cpp	Sat Aug 22 17:26:16 2015
-@@ -60,6 +60,12 @@
-   }
- }
- 
-+static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
-+                      ArgStringList &CmdArgs, const ArgList &Args);
-+
-+static void AddLibgcc(const Driver &D, ArgStringList &CmdArgs,
-+                       const ArgList &Args, const std::string& Exec);
-+
- /// CheckPreprocessingOptions - Perform some validation of preprocessing
- /// arguments that is shared with gcc.
- static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
-@@ -1360,14 +1366,30 @@
-   return "";
- }
- 
-+static const char *getSparcTargetCPU(const ArgList &Args,
-+                                     const llvm::Triple &Triple);
-+
-+static const char *getSparcTargetCPUFeature(const char* CPU,
-+                                            const ArgList &Args,
-+                                            const llvm::Triple &Triple);
-+
- static void getSparcTargetFeatures(const ArgList &Args,
--                                   std::vector<const char *> &Features) {
--  bool SoftFloatABI = true;
-+                                   std::vector<const char *> &Features,
-+                                   const llvm::Triple &Triple) {
-+  bool SoftFloatABI;
-+
-+  if ((Triple.getOS() == llvm::Triple::Solaris) ||
-+      (Triple.getOS() == llvm::Triple::Linux))
-+    SoftFloatABI = false;
-+  else
-+    SoftFloatABI = true;
-+
-   if (Arg *A =
-           Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float)) {
-     if (A->getOption().matches(options::OPT_mhard_float))
-       SoftFloatABI = false;
-   }
-+
-   if (SoftFloatABI)
-     Features.push_back("+soft-float");
- }
-@@ -1375,17 +1397,31 @@
- void Clang::AddSparcTargetArgs(const ArgList &Args,
-                              ArgStringList &CmdArgs) const {
-   const Driver &D = getToolChain().getDriver();
-+  const llvm::Triple &T = getToolChain().getTriple();
- 
-   // Select the float ABI as determined by -msoft-float and -mhard-float.
-+  // There is no support for soft-float ABI in Solaris.
-   StringRef FloatABI;
-   if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
-                                options::OPT_mhard_float)) {
--    if (A->getOption().matches(options::OPT_msoft_float))
-+    if (A->getOption().matches(options::OPT_msoft_float)) {
-+      if ((T.getOS() == llvm::Triple::Solaris) ||
-+          (T.getOS() == llvm::Triple::Linux)) {
-+        D.Diag(diag::warn_drv_clang_unsupported) << "-msoft-float";
-+        D.Diag(diag::warn_drv_overriding_flag_option) <<
-+          "-msoft-float" << "-mhard-float";
-+        FloatABI = "hard";
-+      } else {
-       FloatABI = "soft";
--    else if (A->getOption().matches(options::OPT_mhard_float))
-+      }
-+    } else if (A->getOption().matches(options::OPT_mhard_float))
-       FloatABI = "hard";
-   }
- 
-+  if (((T.getOS() == llvm::Triple::Solaris) ||
-+       (T.getOS() == llvm::Triple::Linux)) && FloatABI.empty())
-+    FloatABI = "hard";
-+
-   // If unspecified, choose the default based on the platform.
-   if (FloatABI.empty()) {
-     // Assume "soft", but warn the user we are guessing.
-@@ -1400,10 +1436,93 @@
-     CmdArgs.push_back("-msoft-float");
-   } else {
-     assert(FloatABI == "hard" && "Invalid float abi!");
--    CmdArgs.push_back("-mhard-float");
-   }
-+
-+  std::string Feature;
-+  if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
-+    Feature = "-march=";
-+    Feature += A->getValue();
-+    CmdArgs.push_back(Args.MakeArgString("-target-feature"));
-+    CmdArgs.push_back(Args.MakeArgString(Feature.c_str()));
- }
- 
-+  if (Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
-+    Feature = "-mtune=";
-+    Feature += A->getValue();
-+    CmdArgs.push_back(Args.MakeArgString("-target-feature"));
-+    CmdArgs.push_back(Args.MakeArgString(Feature.c_str()));
-+  }
-+
-+  if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
-+    Feature = "-mcpu=";
-+    Feature += A->getValue();
-+    CmdArgs.push_back(Args.MakeArgString("-target-feature"));
-+    CmdArgs.push_back(Args.MakeArgString(Feature.c_str()));
-+  }
-+}
-+
-+static const char *getSparcTargetCPU(const ArgList &Args,
-+                                     const llvm::Triple &Triple) {
-+    StringRef V;
-+
-+    if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
-+      V = A->getValue();
-+      switch (Triple.getOS()) {
-+      case llvm::Triple::Solaris:
-+      case llvm::Triple::Linux:
-+        if (V == "v8plus" || V == "v8plusa" ||
-+            V == "v8plusb" || V == "v9" ||
-+            V == "v9a" || V == "v9b" ||
-+            V == "sparcmaf" || V == "sparc4" )
-+          return Args.MakeArgString(V);
-+        break;
-+      default:
-+        return Args.MakeArgString("v8plusa");
-+        break;
-+      }
-+    }
-+
-+    if (Arg *AA = Args.getLastArg(options::OPT_m64))
-+      return "v9a";
-+
-+    return "v8plusa";
-+}
-+
-+static const char *getSparcTargetCPUFeature(const char* CPU,
-+                                            const ArgList &Args,
-+                                            const llvm::Triple &Triple) {
-+  StringRef V;
-+  if (Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
-+    V = A->getValue();
-+
-+    if (V.empty())
-+      if (Arg *AA = Args.getLastArg(options::OPT_m64))
-+        return "vis";
-+
-+    if (V == "ultrasparc" || V == "ultrasparc2" ||
-+        V == "ultrasparc3" || V == "sparcmaf" || V == "sparc4" )
-+      return Args.MakeArgString(A->getValue());
-+  }
-+
-+  if (!CPU)
-+    return 0;
-+
-+  std::string C = CPU;
-+
-+  if (C == "v8plus" || C == "v9")
-+    return "";
-+
-+  if (C == "v8plusa" || C == "v9a")
-+    return "vis1";
-+  else if (C == "v8plusb" || C == "v9b")
-+    return "vis2";
-+  else if (C == "sparcmaf" || C == "sparc4")
-+    return "vis3";
-+
-+  return 0;
-+}
-+
-+
- static const char *getSystemZTargetCPU(const ArgList &Args) {
-   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
-     return A->getValue();
-@@ -1872,7 +1991,7 @@
-     break;
-   case llvm::Triple::sparc:
-   case llvm::Triple::sparcv9:
--    getSparcTargetFeatures(Args, Features);
-+    getSparcTargetFeatures(Args, Features, Triple);
-     break;
-   case llvm::Triple::aarch64:
-   case llvm::Triple::aarch64_be:
-@@ -2695,6 +2814,23 @@
-     }
-   }
- 
-+  // Solaris-specific defaults for PIE
-+  if (getToolChain().getTriple().getOS() == llvm::Triple::Solaris) {
-+    switch (getToolChain().getTriple().getArch()) {
-+    case llvm::Triple::x86:
-+      IsPICLevelTwo = false; // "-fpie"
-+      break;
-+    case llvm::Triple::sparc:
-+    case llvm::Triple::x86_64:
-+    case llvm::Triple::sparcv9:
-+      IsPICLevelTwo = true; // "-fPIE"
-+      break;
-+
-+    default:
-+      break;
-+    }
-+  }
-+
-   // For the PIC and PIE flag options, this logic is different from the
-   // legacy logic in very old versions of GCC, as that logic was just
-   // a bug no one had ever fixed. This logic is both more rational and
-@@ -2740,6 +2876,47 @@
-   if (Args.hasArg(options::OPT_static))
-     PIC = PIE = false;
- 
-+  if (Triple.getOS() == llvm::Triple::Solaris) {
-+    if (Arg *A = Args.getLastArg(options::OPT_shared)) {
-+      PIC = true;
-+      PIE = false;
-+      CmdArgs.push_back("-mrelocation-model");
-+      CmdArgs.push_back("pic");
-+      if (IsPICLevelTwo) {
-+        CmdArgs.push_back("-pic-level");
-+        CmdArgs.push_back("2");
-+      }
-+    } else if (PIC) {
-+      PIC = true;
-+      PIE = false;
-+      CmdArgs.push_back("-mrelocation-model");
-+      CmdArgs.push_back("pic");
-+      if (IsPICLevelTwo) {
-+        CmdArgs.push_back("-pic-level");
-+        CmdArgs.push_back("2");
-+      }
-+    } else if (PIE) {
-+      PIC = PIE = true;
-+      CmdArgs.push_back("-mrelocation-model");
-+      CmdArgs.push_back("pic");
-+      if (IsPICLevelTwo) {
-+        CmdArgs.push_back("-pie-level");
-+        CmdArgs.push_back("2");
-+      }
-+    } else if (Args.hasArg(options::OPT_static)) {
-+      // Solaris doesn't to static relocations.
-+      PIC = PIE = false;
-+      CmdArgs.push_back("-mrelocation-model");
-+      CmdArgs.push_back("dynamic-no-pic");
-+    } else {
-+      // This is a Solaris non-PIE executable.
-+      // Solaris doesn't to static relocations.
-+      PIC = PIE = false;
-+      CmdArgs.push_back("-mrelocation-model");
-+      CmdArgs.push_back("dynamic-no-pic");
-+    }
-+  }
-+
-   if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
-     // This is a very special mode. It trumps the other modes, almost no one
-     // uses it, and it isn't even valid on any OS but Darwin.
-@@ -2762,6 +2939,8 @@
-   } else {
-     // Currently, LLVM only knows about PIC vs. static; the PIE differences are
-     // handled in Clang's IRGen by the -pie-level flag.
-+    // Solaris already took care of PIC/PIE/non-PIC above.
-+    if (Triple.getOS() != llvm::Triple::Solaris) {
-     CmdArgs.push_back("-mrelocation-model");
-     CmdArgs.push_back(PIC ? "pic" : "static");
- 
-@@ -2774,6 +2953,7 @@
-       }
-     }
-   }
-+  }
- 
-   CmdArgs.push_back("-mthread-model");
-   if (Arg *A = Args.getLastArg(options::OPT_mthread_model))
-@@ -3180,12 +3360,13 @@
-       // FIXME: we should support specifying dwarf version with
-       // -gline-tables-only.
-       CmdArgs.push_back("-gline-tables-only");
--      // Default is dwarf-2 for Darwin, OpenBSD, FreeBSD and Solaris.
-+      // Default is dwarf-2 for Darwin, OpenBSD and FreeBSD.
-       const llvm::Triple &Triple = getToolChain().getTriple();
-       if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::OpenBSD ||
--          Triple.getOS() == llvm::Triple::FreeBSD ||
--          Triple.getOS() == llvm::Triple::Solaris)
-+          Triple.getOS() == llvm::Triple::FreeBSD)
-         CmdArgs.push_back("-gdwarf-2");
-+      else if (Triple.getOS() == llvm::Triple::Solaris)
-+        CmdArgs.push_back("-gdwarf-4");
-     } else if (A->getOption().matches(options::OPT_gdwarf_2))
-       CmdArgs.push_back("-gdwarf-2");
-     else if (A->getOption().matches(options::OPT_gdwarf_3))
-@@ -3194,12 +3375,13 @@
-       CmdArgs.push_back("-gdwarf-4");
-     else if (!A->getOption().matches(options::OPT_g0) &&
-              !A->getOption().matches(options::OPT_ggdb0)) {
--      // Default is dwarf-2 for Darwin, OpenBSD, FreeBSD and Solaris.
-+      // Default is dwarf-2 for Darwin, OpenBSD and FreeBSD.
-       const llvm::Triple &Triple = getToolChain().getTriple();
-       if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::OpenBSD ||
--          Triple.getOS() == llvm::Triple::FreeBSD ||
--          Triple.getOS() == llvm::Triple::Solaris)
-+          Triple.getOS() == llvm::Triple::FreeBSD)
-         CmdArgs.push_back("-gdwarf-2");
-+      else if (Triple.getOS() == llvm::Triple::Solaris)
-+        CmdArgs.push_back("-gdwarf-4");
-       else
-         CmdArgs.push_back("-g");
-     }
-@@ -3594,6 +3776,7 @@
-     // If -fmessage-length=N was not specified, determine whether this is a
-     // terminal and, if so, implicitly define -fmessage-length appropriately.
-     unsigned N = llvm::sys::Process::StandardErrColumns();
-+    if (N == 0) N = 72U;
-     CmdArgs.push_back(Args.MakeArgString(Twine(N)));
-   }
- 
-@@ -3735,6 +3918,7 @@
-     CmdArgs.push_back("-backend-option");
-     CmdArgs.push_back("-force-align-stack");
-   }
-+
-   if (!Args.hasFlag(options::OPT_mno_stackrealign, options::OPT_mstackrealign,
-                    false)) {
-     CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
-@@ -3743,6 +3927,10 @@
-   if (Args.hasArg(options::OPT_mstack_alignment)) {
-     StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
-     CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
-+  } else {
-+    if ((getToolChain().getTriple().getArch() == llvm::Triple::sparc) ||
-+        (getToolChain().getTriple().getArch() == llvm::Triple::sparcv9))
-+      CmdArgs.push_back("-mstack-alignment=16");
-   }
- 
-   if (getToolChain().getTriple().getArch() == llvm::Triple::aarch64 ||
-@@ -6049,6 +6237,10 @@
-   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
- }
- 
-+void solaris::Assemble::RenderExtraToolArgs(const JobAction &JA,
-+                                            ArgStringList &CmdArgs) const {
-+}
-+
- void solaris::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
-                                       const InputInfo &Output,
-                                       const InputInfoList &Inputs,
-@@ -6055,61 +6247,321 @@
-                                       const ArgList &Args,
-                                       const char *LinkingOutput) const {
-   claimNoWarnArgs(Args);
-+
-+  const toolchains::Solaris &TC =
-+    static_cast<const toolchains::Solaris&>(getToolChain());
-+
-+  if (!TC.isValid()) {
-+    llvm::errs() << "Invalid GCC installation!\n";
-+    return;
-+  }
-+
-+  const llvm::Triple &TT = TC.getTriple();
-+  const Driver &D = TC.getDriver();
-+  llvm::Triple::ArchType Arch = TT.getArch();
-+  StringRef Assembler = TC.getAssembler();
-+  bool m32 = true;
-+
-+  std::string march;
-+  std::string mtune;
-+  std::string mcpu;
-+
-   ArgStringList CmdArgs;
- 
--  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
--                       options::OPT_Xassembler);
-+  if (Arg *A = Args.getLastArg(options::OPT_march_EQ))
-+    march = A->getValue();
-+  else
-+    march = TC.getMArch();
- 
-+  if (Arg *A = Args.getLastArg(options::OPT_mtune_EQ))
-+    mtune = A->getValue();
-+  else
-+    mtune = TC.getMTune();
-+
-+  if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
-+    mcpu = A->getValue();
-+  else
-+    mcpu = TC.getMCpu();
-+
-+  if (Arg *A = Args.getLastArg(options::OPT_m64))
-+    m32 = false;
-+
-+  if (Args.hasArg(options::OPT_v))
-+    CmdArgs.push_back("-V");
-+
-+  switch (Arch) {
-+  case llvm::Triple::x86:
-+  case llvm::Triple::x86_64:
-+    if (m32)
-+      CmdArgs.push_back("--32");
-+    else
-+      CmdArgs.push_back("--64");
-+    break;
-+  case llvm::Triple::sparc:
-+  case llvm::Triple::sparcv9:
-+    if (m32) {
-+      CmdArgs.push_back("-32");
-+      march="v8plusa";
-+      mcpu="v8plusa";
-+    } else {
-+      CmdArgs.push_back("-64");
-+      march="v9a";
-+      mcpu="v9a";
-+    }
-+    break;
-+  default:
-+    D.Diag(diag::err_target_unsupported_arch) << TT.getArchName()
-+      << TT.getTriple();
-+    break;
-+  }
-+
-+  std::string xarch;
-+
-+  switch (Arch) {
-+    case llvm::Triple::sparc:
-+    case llvm::Triple::sparcv9:
-+      if (!march.empty()) {
-+        xarch = "-xarch=";
-+        xarch += march;
-+        CmdArgs.push_back(Args.MakeArgString(xarch.c_str()));
-+      } else if (!mtune.empty()) {
-+        xarch = "-xarch=";
-+        xarch += mtune;
-+        CmdArgs.push_back(Args.MakeArgString(xarch.c_str()));
-+      } else if (!mcpu.empty()) {
-+        xarch = "-xarch=";
-+        xarch += mcpu;
-+        CmdArgs.push_back(Args.MakeArgString(xarch.c_str()));
-+      }
-+
-+      addAssemblerKPIC(Args, CmdArgs);
-+
-+      if (Args.hasArg(options::OPT_mstrict_align))
-+        CmdArgs.push_back("--enforce-aligned-data");
-+      break;
-+    case llvm::Triple::x86:
-+    case llvm::Triple::x86_64:
-+      if (!march.empty()) {
-+        xarch = "-mtune=";
-+        xarch += march;
-+        CmdArgs.push_back(Args.MakeArgString(xarch.c_str()));
-+      } else if (!mtune.empty()) {
-+        xarch = "-mtune=";
-+        xarch += mtune;
-+        CmdArgs.push_back(Args.MakeArgString(xarch.c_str()));
-+      }
-+      if (!mcpu.empty()) {
-+        xarch = "-march=";
-+        xarch += mcpu;
-+        CmdArgs.push_back(Args.MakeArgString(xarch.c_str()));
-+      }
-+      break;
-+    default:
-+      D.Diag(diag::err_target_unsupported_arch) << TT.getArchName()
-+        << TT.getTriple();
-+      break;
-+  }
-+
-+  if (Args.hasArg(options::OPT_g_Flag) || Args.hasArg(options::OPT_g0) ||
-+      Args.hasArg(options::OPT_g1) || Args.hasArg(options::OPT_g2) ||
-+      Args.hasArg(options::OPT_g3))
-+    CmdArgs.push_back("--gen-debug");
-+
-+  if (Output.isFilename()) {
-   CmdArgs.push_back("-o");
-   CmdArgs.push_back(Output.getFilename());
-+  } else {
-+    D.Diag(diag::err_drv_invalid_gcc_output_type) << "<unspecified>";
-+    CmdArgs.push_back("-fsyntax-only");
-+  }
- 
--  for (const auto &II : Inputs)
-+  RenderExtraToolArgs(JA, CmdArgs);
-+
-+  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
-+                       options::OPT_Xassembler);
-+
-+  for (const auto &II : Inputs) {
-+    if (II.getType() == types::TY_LLVM_IR ||
-+        II.getType() == types::TY_LTO_IR ||
-+        II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
-+      D.Diag(clang::diag::err_drv_no_linker_llvm_support)
-+        << getToolChain().getTripleString();
-+    else if (II.getType() == types::TY_AST)
-+      D.Diag(clang::diag::err_drv_no_ast_support)
-+        << getToolChain().getTripleString();
-+    else if (II.getType() == types::TY_ModuleFile)
-+      D.Diag(diag::err_drv_no_module_support)
-+        << getToolChain().getTripleString();
-+
-+    if (II.isFilename())
-     CmdArgs.push_back(II.getFilename());
-+    else
-+      II.getInputArg().render(Args, CmdArgs);
-+  }
- 
--  const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
--  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
-+  C.addCommand(llvm::make_unique<Command>(JA, *this,
-+                                          Args.MakeArgString(Assembler),
-+                                          CmdArgs));
- }
- 
-+
-+void solaris::Link::RenderExtraToolArgs(const JobAction &JA,
-+                                        ArgStringList &CmdArgs) const {
-+}
-+
- void solaris::Link::ConstructJob(Compilation &C, const JobAction &JA,
-                                   const InputInfo &Output,
-                                   const InputInfoList &Inputs,
-                                   const ArgList &Args,
-                                   const char *LinkingOutput) const {
--  // FIXME: Find a real GCC, don't hard-code versions here
--  std::string GCCLibPath = "/usr/gcc/4.5/lib/gcc/";
--  const llvm::Triple &T = getToolChain().getTriple();
--  std::string LibPath = "/usr/lib/";
-+  const toolchains::Solaris& TC =
-+    static_cast<const toolchains::Solaris&>(getToolChain());
-+
-+  if (!TC.isValid()) {
-+    llvm::errs() << "Invalid GCC installation!\n";
-+    return;
-+  }
-+
-+  const llvm::Triple &T = TC.getTriple();
-+  const Driver &D = TC.getDriver();
-   llvm::Triple::ArchType Arch = T.getArch();
-+  bool m32 = true;
-+  StringRef Linker = TC.getLinker();
-+
-+  if (Arg *A = Args.getLastArg(options::OPT_m64))
-+    m32 = false;
-+
-+  std::string GCCLibPath;
-+  std::string YPPath;
-+  GCCLibPath += "/lib/gcc/";
-+  std::string LibPath = "/usr/lib/";
-+  std::string ShortLibPath = "/lib/";
-+  std::string ClangLibPath;
-+  const char* moption;
-+
-   switch (Arch) {
-   case llvm::Triple::x86:
--    GCCLibPath +=
--        ("i386-" + T.getVendorName() + "-" + T.getOSName()).str() + "/4.5.2/";
-+    if (m32) {
-+      GCCLibPath = TC.getGCCInternalLibDir().str();
-+      GCCLibPath += "/";
-+      moption = "-32";
-+      YPPath = "/lib:/usr/lib";
-+      ClangLibPath = "/usr/lib/clang/";
-+    } else {
-+      GCCLibPath = TC.getGCCInternalMultiLibDir().str();
-+      GCCLibPath += "/";
-+      LibPath += "amd64/";
-+      ShortLibPath += "amd64/";
-+      moption = "-64";
-+      YPPath = "/lib/amd64:/usr/lib/amd64";
-+      ClangLibPath = "/usr/lib/clang/amd64/";
-+    }
-     break;
-+  case llvm::Triple::sparc:
-+    if (m32) {
-+      GCCLibPath = TC.getGCCInternalLibDir().str();
-+      GCCLibPath += "/";
-+      moption = "-32";
-+      YPPath = "/lib:/usr/lib";
-+      ClangLibPath = "/usr/lib/clang/";
-+    } else {
-+      GCCLibPath = TC.getGCCInternalMultiLibDir().str();
-+      GCCLibPath += "/";
-+      LibPath += "sparcv9/";
-+      ShortLibPath += "sparcv9/";
-+      moption = "-64";
-+      YPPath = "/lib/sparcv9:/usr/lib/sparcv9";
-+      ClangLibPath = "/usr/lib/clang/sparcv9/";
-+    }
-+    break;
-   case llvm::Triple::x86_64:
--    GCCLibPath += ("i386-" + T.getVendorName() + "-" + T.getOSName()).str();
--    GCCLibPath += "/4.5.2/amd64/";
-+    if (m32) {
-+      GCCLibPath = TC.getGCCInternalMultiLibDir().str();
-+      GCCLibPath += "/";
-+      moption = "-32";
-+      YPPath = "/lib:/usr/lib";
-+      ClangLibPath = "/usr/lib/clang/";
-+    } else {
-+      GCCLibPath = TC.getGCCInternalLibDir().str();
-+      GCCLibPath += "/";
-     LibPath += "amd64/";
-+      ShortLibPath += "amd64/";
-+      moption = "-64";
-+      YPPath = "/lib/amd64:/usr/lib/amd64";
-+      ClangLibPath = "/usr/lib/clang/amd64/";
-+    }
-     break;
-+  case llvm::Triple::sparcv9:
-+    if (m32) {
-+      GCCLibPath = TC.getGCCInternalMultiLibDir().str();
-+      GCCLibPath += "/";
-+      moption = "-32";
-+      YPPath = "/lib:/usr/lib";
-+      ClangLibPath = "/usr/lib/clang/";
-+    } else {
-+      GCCLibPath = TC.getGCCInternalLibDir().str();
-+      GCCLibPath += "/";
-+      LibPath += "sparcv9/";
-+      ShortLibPath += "sparcv9/";
-+      moption = "-64";
-+      YPPath = "/lib/sparcv9:/usr/lib/sparcv9";
-+      ClangLibPath = "/usr/lib/clang/sparcv9/";
-+    }
-+    break;
-   default:
--    llvm_unreachable("Unsupported architecture");
-+    D.Diag(diag::err_target_unsupported_arch) << T.getArchName()
-+      << T.getTriple();
-+    break;
-   }
- 
-   ArgStringList CmdArgs;
- 
--  // Demangle C++ names in errors
--  CmdArgs.push_back("-C");
-+  CmdArgs.push_back(Args.MakeArgString("-zignore"));
- 
--  if ((!Args.hasArg(options::OPT_nostdlib)) &&
--      (!Args.hasArg(options::OPT_shared))) {
--    CmdArgs.push_back("-e");
--    CmdArgs.push_back("_start");
-+  Arg *PIEArg = Args.getLastArg(options::OPT_fPIE, options::OPT_fpie);
-+  if (PIEArg) {
-+    if (PIEArg->getOption().matches(options::OPT_fPIE) ||
-+        PIEArg->getOption().matches(options::OPT_fpie)) {
-+      CmdArgs.push_back(Args.MakeArgString("-Qy"));
-+      CmdArgs.push_back(Args.MakeArgString("-zdirect"));
-+      CmdArgs.push_back(Args.MakeArgString("-ztextwarn"));
-+      CmdArgs.push_back(Args.MakeArgString("-ztype=pie"));
-+      CmdArgs.push_back(Args.MakeArgString("-zaslr=enable"));
-   }
-+  }
- 
-+  // Silence warning for "-g: argument not used during compilation
-+  Args.ClaimAllArgs(options::OPT_g_Group);
-+
-+  // Language options
-+  Args.ClaimAllArgs(options::OPT_emit_llvm);
-+  Args.ClaimAllArgs(options::OPT_w);
-+
-+  if (Args.hasArg(options::OPT_s))
-+    CmdArgs.push_back("-s");
-+
-+  const std::vector<std::string> &ExtraOpts = TC.getExtraOpts();
-+
-+  // Handle extra options
-+  if (ExtraOpts.size()) {
-+    for (std::vector<std::string>::const_iterator I = ExtraOpts.begin(),
-+         E = ExtraOpts.end(); I != E; ++I)
-+      CmdArgs.push_back((*I).c_str());
-+  }
-+
-+  // Demangle C++ names
-+  if (Linker == "/usr/gnu/bin/ld.bfd" || Linker == "/usr/gnu/bin/ld.gold" ||
-+      Linker == "/usr/gnu/bin/ld" || Linker == "/usr/bin/gld")
-+    CmdArgs.push_back("--demangle");
-+  else if (Linker == "/usr/bin/ld")
-+    CmdArgs.push_back("-C");
-+
-   if (Args.hasArg(options::OPT_static)) {
-     CmdArgs.push_back("-Bstatic");
-     CmdArgs.push_back("-dn");
-   } else {
-     CmdArgs.push_back("-Bdynamic");
-+    CmdArgs.push_back("-dy");
-     if (Args.hasArg(options::OPT_shared)) {
-       CmdArgs.push_back("-shared");
-     } else {
-@@ -6125,41 +6577,261 @@
-     assert(Output.isNothing() && "Invalid output.");
-   }
- 
-+  const char* Values = "values-Xa.o";
-+  const char* Xpg = "values-xpg4.o";
-+
-+  Arg *STDArg = Args.getLastArg(options::OPT_std_EQ);
-+  if (STDArg) {
-+    if (STDArg->getOption().matches(options::OPT_std_EQ)) {
-+      std::string Lang = STDArg->getValue();
-+      if ((Lang == "c99") || (Lang == "c11") ||
-+          (Lang == "c++11") || (Lang == "c++14")) {
-+        Values = "values-Xc.o";
-+        Xpg = "values-xpg6.o";
-+      }
-+    }
-+  }
-+
-+  const char *gldm = 0;
-+  if (Linker == "/usr/gnu/bin/ld.bfd" || Linker == "/usr/gnu/bin/ld.gold" ||
-+      Linker == "/usr/gnu/bin/ld" || Linker == "/usr/bin/gld") {
-+    switch (Arch) {
-+    case llvm::Triple::x86:
-+      if (m32)
-+        gldm = "-m elf_i386";
-+      else
-+        gldm = "-m elf_x86_64";
-+      break;
-+    case llvm::Triple::x86_64:
-+      if (m32)
-+        gldm = "-m elf_i386";
-+      else
-+        gldm = "-m elf_x86_64";
-+      break;
-+    case llvm::Triple::sparc:
-+      if (m32)
-+        gldm = "-m elf32_sparc";
-+      else
-+        gldm = "-m elf64_sparc";
-+      break;
-+    case llvm::Triple::sparcv9:
-+      if (m32)
-+        gldm = "-m elf32_sparc";
-+      else
-+        gldm = "-m elf64_sparc";
-+      break;
-+    default:
-+      break;
-+    }
-+
-+    if (gldm)
-+      CmdArgs.push_back(Args.MakeArgString(StringRef(gldm)));
-+
-+    if (Linker == "/usr/gnu/bin/ld.gold") {
-+      if (Args.hasArg(options::OPT_O))
-+        Args.AddAllArgs(CmdArgs, options::OPT_O);
-+    }
-+  }
-+
-+  if (Args.hasArg(options::OPT_v))
-+    CmdArgs.push_back(Args.MakeArgString(StringRef("-V")));
-+
-+  CmdArgs.push_back(Args.MakeArgString(StringRef("-Qy")));
-+  if (Linker == "/usr/bin/ld") {
-+    CmdArgs.push_back(Args.MakeArgString(StringRef("-Y")));
-+    CmdArgs.push_back(Args.MakeArgString(StringRef("P," + YPPath)));
-+  } else {
-+    CmdArgs.push_back(Args.MakeArgString(StringRef("-Y")));
-+    CmdArgs.push_back(Args.MakeArgString(StringRef(YPPath)));
-+  }
-+
-+  CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
-+
-+  std::string P = GCCLibPath;
-+  P += "../../..";
-+  CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + P));
-+
-+  std::string crt1o;
-+
-   if (!Args.hasArg(options::OPT_nostdlib) &&
-       !Args.hasArg(options::OPT_nostartfiles)) {
-     if (!Args.hasArg(options::OPT_shared)) {
--      CmdArgs.push_back(Args.MakeArgString(LibPath + "crt1.o"));
-+      switch (Arch) {
-+      case llvm::Triple::sparc:
-+      case llvm::Triple::sparcv9:
-+        crt1o = GCCLibPath;
-+        break;
-+      case llvm::Triple::x86:
-+      case llvm::Triple::x86_64:
-+        crt1o = LibPath;
-+        break;
-+      default:
-+        D.Diag(diag::err_target_unsupported_arch) << T.getArchName()
-+          << T.getTriple();
-+        break;
-+      }
-+
-+      crt1o += "/crt1.o";
-+
-+      CmdArgs.push_back(Args.MakeArgString(crt1o.c_str()));
-       CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
--      CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
-+      CmdArgs.push_back(Args.MakeArgString(LibPath + Values));
-+      CmdArgs.push_back(Args.MakeArgString(LibPath + Xpg));
-+      CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + GCCLibPath));
-+      CmdArgs.push_back(Args.MakeArgString("-L" + P));
-       CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
-     } else {
-       CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
--      CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
-+      CmdArgs.push_back(Args.MakeArgString(LibPath + Values));
-+      CmdArgs.push_back(Args.MakeArgString(LibPath + Xpg));
-+      CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + GCCLibPath));
-+      CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + P));
-       CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
-     }
--    if (getToolChain().getDriver().CCCIsCXX())
--      CmdArgs.push_back(Args.MakeArgString(LibPath + "cxa_finalize.o"));
-+  } else if (Args.hasArg(options::OPT_nostdlib) &&
-+             !Args.hasArg(options::OPT_nostartfiles)) {
-+    if (Args.hasArg(options::OPT_shared)) {
-+      CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
-+      CmdArgs.push_back(Args.MakeArgString(LibPath + Values));
-+      CmdArgs.push_back(Args.MakeArgString(LibPath + Xpg));
-+      CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + GCCLibPath));
-+      CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + P));
-+      CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
-+    } else {
-+      CmdArgs.push_back(Args.MakeArgString(crt1o.c_str()));
-+      CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
-+      CmdArgs.push_back(Args.MakeArgString(LibPath + Values));
-+      CmdArgs.push_back(Args.MakeArgString(LibPath + Xpg));
-+      CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + GCCLibPath));
-+      CmdArgs.push_back(Args.MakeArgString("-L" + P));
-   }
-+  } else if (!Args.hasArg(options::OPT_nostdlib) &&
-+             Args.hasArg(options::OPT_nostartfiles)) {
-+    if (Args.hasArg(options::OPT_shared)) {
-+      CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtend.o"));
-+    }
-+  }
- 
--  CmdArgs.push_back(Args.MakeArgString("-L" + GCCLibPath));
-+  // Itanium C++ ABI.
-+  std::string CXAFinalize;
-+  bool HasSystemCXAFinalize = false;
- 
-+  if (!Args.hasArg(options::OPT_shared)) {
-+    if (PIEArg) {
-+      if (PIEArg->getOption().matches(options::OPT_fPIE) ||
-+          PIEArg->getOption().matches(options::OPT_fpie)) {
-+        CXAFinalize = ClangLibPath + "cxa_finalize_pic.o";
-+      }
-+    } else {
-+      CXAFinalize = ClangLibPath + "cxa_finalize.o";
-+    }
-+
-+    HasSystemCXAFinalize = llvm::sys::fs::exists(CXAFinalize.c_str());
-+
-+    if (D.CCCIsCXX() && HasSystemCXAFinalize)
-+      CmdArgs.push_back(Args.MakeArgString(CXAFinalize.c_str()));
-+  }
-+
-+  CmdArgs.push_back(Args.MakeArgString(StringRef("-L" + GCCLibPath)));
-+  CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
-+  CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + ShortLibPath));
-+
-   Args.AddAllArgs(CmdArgs, options::OPT_L);
-+  const ToolChain::path_list Paths = TC.getFilePaths();
-+  for (ToolChain::path_list::const_iterator B = Paths.begin(), E = Paths.end();
-+       B != E; ++B) {
-+    CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + *B));
-+
-+    // Itanium C++ ABI.
-+    if (!Args.hasArg(options::OPT_shared)) {
-+      if (D.CCCIsCXX() && !HasSystemCXAFinalize) {
-+        if (PIEArg) {
-+          if (PIEArg->getOption().matches(options::OPT_fPIE) ||
-+              PIEArg->getOption().matches(options::OPT_fpie)) {
-+            CXAFinalize = *B + "/cxa_finalize_pic.o";
-+          }
-+        } else {
-+          CXAFinalize = *B + "/cxa_finalize.o";
-+        }
-+
-+        if (llvm::sys::fs::exists(CXAFinalize.c_str()))
-+          CmdArgs.push_back(Args.MakeArgString(CXAFinalize.c_str()));
-+      }
-+    }
-+  }
-+
-   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
-   Args.AddAllArgs(CmdArgs, options::OPT_e);
-+  Args.AddAllArgs(CmdArgs, options::OPT_s);
-+  Args.AddAllArgs(CmdArgs, options::OPT_t);
-   Args.AddAllArgs(CmdArgs, options::OPT_r);
- 
--  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
-+  std::vector<std::string>  zoptions = Args.getAllArgValues(options::OPT_z);
-+  std::string zoption;
- 
-+  for (std::vector<std::string>::const_iterator B = zoptions.begin(),
-+      E = zoptions.end(); B != E; ++B) {
-+    zoption = "-z";
-+    zoption += *B;
-+    CmdArgs.push_back(Args.MakeArgString(StringRef(zoption)));
-+  }
-+
-+  if (!Args.hasArg(options::OPT_mimpure_text) &&
-+      !Args.hasArg(options::OPT_fpie) &&
-+      !Args.hasArg(options::OPT_fPIE))
-+    CmdArgs.push_back(Args.MakeArgString(StringRef("-ztext")));
-+
-+  // Itanium C++ ABI.
-+  if (D.CCCIsCXX()) {
-+    if (!Args.hasArg(options::OPT_shared)) {
-+      const char* zfiniarray = "-zfiniarray=__cxa_finalize";
-+      CmdArgs.push_back(Args.MakeArgString(zfiniarray));
-+    }
-+  }
-+
-+  if (Linker == "/usr/gnu/bin/ld.gold" || Linker == "/usr/gnu/bin/ld" ||
-+      Linker == "/usr/gnu/bin/ld.bfd") {
-+    CmdArgs.push_back("-plugin");
-+    std::string Plugin = D.Dir + "/../lib/LLVMgold.so";
-+    CmdArgs.push_back(Args.MakeArgString(Plugin));
-+  } else {
-+    CmdArgs.push_back(moption);
-+  }
-+
-+  if (Arg *A = Args.getLastArg(options::OPT_rpath)) {
-+    StringRef V = A->getValue();
-+    if (Linker == "/usr/gnu/bin/ld.gold" || Linker == "/usr/gnu/bin/ld" ||
-+        Linker == "/usr/gnu/bin/ld.bfd") {
-+      CmdArgs.push_back(Args.MakeArgString("-rpath"));
-+      CmdArgs.push_back(Args.MakeArgString(V));
-+    } else {
-+      CmdArgs.push_back(Args.MakeArgString("-R"));
-+      CmdArgs.push_back(Args.MakeArgString(V));
-+    }
-+  }
-+
-+  AddLinkerInputs(TC, Inputs, Args, CmdArgs);
-+  AddLibgcc(D, CmdArgs, Args, Linker.str());
-+
-   if (!Args.hasArg(options::OPT_nostdlib) &&
-       !Args.hasArg(options::OPT_nodefaultlibs)) {
--    if (getToolChain().getDriver().CCCIsCXX())
--      getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
--    CmdArgs.push_back("-lgcc_s");
--    if (!Args.hasArg(options::OPT_shared)) {
--      CmdArgs.push_back("-lgcc");
-+    if (D.CCCIsCXX())
-+      TC.AddCXXStdlibLibArgs(Args, CmdArgs);
-+
-       CmdArgs.push_back("-lc");
-       CmdArgs.push_back("-lm");
-+    CmdArgs.push_back("-lgcc_s");
-+
-+    if (Args.hasArg(options::OPT_static)) {
-+      CmdArgs.push_back("-lgcc");
-+      CmdArgs.push_back("-lgcc_eh");
-     }
-+  } else if (Args.hasArg(options::OPT_nostdlib) &&
-+             (!Args.hasArg(options::OPT_nodefaultlibs))) {
-+    CmdArgs.push_back("-lgcc_s");
-+
-+    if (Args.hasArg(options::OPT_static))
-+      CmdArgs.push_back("-lgcc_eh");
-   }
- 
-   if (!Args.hasArg(options::OPT_nostdlib) &&
-@@ -6166,15 +6838,17 @@
-       !Args.hasArg(options::OPT_nostartfiles)) {
-     CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtend.o"));
-   }
-+
-   CmdArgs.push_back(Args.MakeArgString(LibPath + "crtn.o"));
- 
--  addProfileRT(getToolChain(), Args, CmdArgs);
-+  addProfileRT(TC, Args, CmdArgs);
- 
--  const char *Exec =
--    Args.MakeArgString(getToolChain().GetLinkerPath());
--  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
-+  C.addCommand(llvm::make_unique<Command>(JA, *this,
-+                                          Args.MakeArgString(Linker),
-+                                          CmdArgs));
- }
- 
-+
- void openbsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
-                                      const InputInfo &Output,
-                                      const InputInfoList &Inputs,
-@@ -7280,6 +7954,40 @@
-   if (isAndroid && !StaticLibgcc)
-     CmdArgs.push_back("-ldl");
- }
-+
-+static void AddLibgcc(const Driver &D, ArgStringList &CmdArgs,
-+                      const ArgList &Args, const std::string& Exec) {
-+  bool StaticLibgcc = Args.hasArg(options::OPT_static) ||
-+    Args.hasArg(options::OPT_static_libgcc);
-+  if (!D.CCCIsCXX())
-+    CmdArgs.push_back("-lgcc");
-+
-+  if (StaticLibgcc) {
-+    if (D.CCCIsCXX())
-+      CmdArgs.push_back("-lgcc");
-+  } else {
-+    if ((!D.CCCIsCXX()) && ((Exec == "/usr/bin/gld") ||
-+                            (Exec == "/usr/gnu/bin/ld") ||
-+                            (Exec == "/usr/gnu/bin/ld.bfd") ||
-+                            (Exec == "/usr/gnu/bin/ld.gold")))
-+      CmdArgs.push_back("--as-needed");
-+
-+    CmdArgs.push_back("-lgcc_s");
-+    if ((!D.CCCIsCXX()) && ((Exec == "/usr/bin/gld") ||
-+                            (Exec == "/usr/gnu/bin/ld") ||
-+                            (Exec == "/usr/gnu/bin/ld.bfd") ||
-+                            (Exec == "/usr/gnu/bin/ld.gold")))
-+      CmdArgs.push_back("--no-as-needed");
-+  }
-+
-+  if (StaticLibgcc)
-+    CmdArgs.push_back("-lgcc_eh");
-+  else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
-+    CmdArgs.push_back("-lgcc");
-+
-+  if (!StaticLibgcc)
-+    CmdArgs.push_back("-ldl");
-+}
- 
- static std::string getLinuxDynamicLinker(const ArgList &Args,
-                                          const toolchains::Linux &ToolChain) {
---- tools/clang/lib/Driver/ToolChains.h	2015-08-29 19:24:32.064113013 -0700
-+++ tools/clang/lib/Driver/ToolChains.h	2015-08-30 12:42:03.657485673 -0700
-@@ -508,16 +508,106 @@
-                              llvm::opt::ArgStringList &CC1Args) const override;
- };
- 
--class LLVM_LIBRARY_VISIBILITY Solaris : public Generic_GCC {
-+class LLVM_LIBRARY_VISIBILITY Solaris : public Generic_ELF {
- public:
-   Solaris(const Driver &D, const llvm::Triple &Triple,
-           const llvm::opt::ArgList &Args);
- 
--  bool IsIntegratedAssemblerDefault() const override { return true; }
-+  bool IsIntegratedAssemblerDefault() const override { return !UseGnuAs; }
-+
-+  std::string computeSysRoot() const;
-+
-+  bool addLibStdCXXIncludePaths(Twine Base, Twine Suffix,
-+                                StringRef GCCTriple,
-+                                StringRef GCCMultiarchTriple,
-+                                StringRef TargetMultiarchTriple,
-+                                Twine IncludeSuffix,
-+                                const llvm::opt::ArgList &DriverArgs,
-+                                llvm::opt::ArgStringList &CC1Args) const;
-+
-+  void addLibStdCXXIncludePaths(Twine Base, Twine TargetArchDir,
-+                                const llvm::opt::ArgList &DriverArgs,
-+                                llvm::opt::ArgStringList &CC1Args) const;
-+
-+  void AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs,
-+                                    llvm::opt::ArgStringList &CC1Args) const override;
-+
-+  void AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs,
-+                                 llvm::opt::ArgStringList &CC1Args) const override;
-+
-+  void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
-+                             llvm::opt::ArgStringList &CC1Args) const override;
-+
-+  void findGCCMajorMinor() const;
-+  void findGCCMajorMinorMicro(const llvm::Triple &Triple) const;
-+  void findGCCIncludeDirs(const llvm::Triple &Triple,
-+                          const llvm::opt::ArgList &Args) const;
-+  void findGCCInternalLibDir(const llvm::Triple &Triple,
-+                             const llvm::opt::ArgList &Args) const;
-+  void findSpecifiedGCCToolchain(const char *StartingPath,
-+                                 const llvm::Triple &Triple,
-+                                 const llvm::opt::ArgList &Args) const;
-+
-+  StringRef getAssembler() const { return Assembler.c_str(); }
-+  StringRef getLinker() const { return Linker.c_str(); }
-+  StringRef getGCCInstallDir() const { return GCCInstallDir.c_str(); }
-+  StringRef getGCCMajorMinor() const { return GCCMajorMinor.c_str(); }
-+  StringRef getMArch() const { return march.c_str(); }
-+  StringRef getMTune() const { return mtune.c_str(); }
-+  StringRef getMCpu() const { return mcpu.c_str(); }
-+  StringRef getGCCInternalLibDir() const { return GCCInternalLibDir; }
-+
-+  StringRef getGCCInternalMultiLibDir() const {
-+    return GCCInternalMultiLibDir;
-+  }
-+
-+  StringRef getGCCMajorMinorMicro() const {
-+    return GCCMajorMinorMicro.c_str();
-+  }
-+
-+  const std::vector<std::string> &getGCCIncludeDirs() const {
-+    return GCCIncludeDirs;
-+  }
-+
-+  const std::vector<std::string> &getExtraOpts() const {
-+    return ExtraOpts;
-+  }
-+
-+  bool isValid() const { return IsValid; }
-+
-+  void print(raw_ostream &OS) const;
-+
- protected:
-   Tool *buildAssembler() const override;
-   Tool *buildLinker() const override;
-+  void validate();
-+
-+private:
-+  bool UseGnuAs;
-+  bool UseGnuLd;
-+  bool UseGoldLd;
-+  bool UseSunLd;
-+  mutable bool UseMediatedGCCToolChainPath;
-+  mutable bool UseSpecifiedGCCToolChainPath;
-+  bool IsValid;
-+
-+protected:
-+  mutable std::string GCCInstallDir;
-+  mutable std::string GCCMajorMinor;
-+  mutable std::string GCCMajorMinorMicro;
-+  mutable std::string GCCInternalLibDir;
-+  mutable std::string GCCInternalMultiLibDir;
-+  mutable std::vector<std::string> GCCIncludeDirs;
-+
-+  mutable std::string Assembler;
-+  mutable std::string Linker;
-+  mutable std::string mtune;
-+  mutable std::string march;
-+  mutable std::string mcpu;
- 
-+  mutable std::vector<std::string> ExtraOpts;
-+  static const char *MediatedGCCToolChainPath;
-+  static const bool SupportsClangLibCPlusPlus;
- };
- 
- 
---- tools/clang/lib/Driver/ToolChains.cpp	2015-04-27 01:13:25.000000000 -0700
-+++ tools/clang/lib/Driver/ToolChains.cpp	2015-08-30 13:11:52.217344511 -0700
-@@ -28,8 +28,10 @@
- #include "llvm/Support/FileSystem.h"
- #include "llvm/Support/MemoryBuffer.h"
- #include "llvm/Support/Path.h"
-+#include "llvm/Support/Host.h"
- #include "llvm/Support/Program.h"
- #include "llvm/Support/raw_ostream.h"
-+
- #include <cstdlib> // ::getenv
- #include <system_error>
- 
-@@ -38,6 +40,19 @@
- using namespace clang;
- using namespace llvm::opt;
- 
-+#if defined(LLVM_ON_UNIX)
-+#include <cstring>
-+#include <cctype>
-+#include <sys/types.h>
-+#include <sys/stat.h>
-+#include <dirent.h>
-+#include <unistd.h>
-+#endif
-+
-+/// \brief Get our best guess at the multiarch triple for a target.
-+static std::string getMultiarchTriple(const llvm::Triple &TargetTriple,
-+                                      StringRef SysRoot);
-+
- MachO::MachO(const Driver &D, const llvm::Triple &Triple,
-                        const ArgList &Args)
-   : ToolChain(D, Triple, Args) {
-@@ -1214,6 +1229,11 @@
-     // If we have a SysRoot, try that first.
-     if (!D.SysRoot.empty()) {
-       Prefixes.push_back(D.SysRoot);
-+
-+      // Add Solaris-specific GCC locations.
-+      if (TargetTriple.getOS() == llvm::Triple::Solaris)
-+        Prefixes.push_back("/usr/gcc");
-+
-       Prefixes.push_back(D.SysRoot + "/usr");
-     }
- 
-@@ -1303,20 +1323,24 @@
-   static const char *const ARMebHFTriples[] = { "armeb-linux-gnueabihf",
-                                                 "armebv7hl-redhat-linux-gnueabi" };
- 
--  static const char *const X86_64LibDirs[] = { "/lib64", "/lib" };
-+  static const char *const X86_64LibDirs[] = { "/lib64", "/lib/amd64",
-+                                               "/lib/64", "/lib" };
-   static const char *const X86_64Triples[] = {
-     "x86_64-linux-gnu", "x86_64-unknown-linux-gnu", "x86_64-pc-linux-gnu",
-     "x86_64-redhat-linux6E", "x86_64-redhat-linux", "x86_64-suse-linux",
-     "x86_64-manbo-linux-gnu", "x86_64-linux-gnu", "x86_64-slackware-linux",
--    "x86_64-linux-android", "x86_64-unknown-linux"
-+    "x86_64-linux-android", "x86_64-unknown-linux", "x86_64-pc-solaris2.11",
-+    "x86_64-pc-solaris2.12", "x86_64-pc-solaris2.13"
-   };
-+
-   static const char *const X32LibDirs[] = { "/libx32" };
-   static const char *const X86LibDirs[] = { "/lib32", "/lib" };
-   static const char *const X86Triples[] = {
-     "i686-linux-gnu", "i686-pc-linux-gnu", "i486-linux-gnu", "i386-linux-gnu",
-     "i386-redhat-linux6E", "i686-redhat-linux", "i586-redhat-linux",
-     "i386-redhat-linux", "i586-suse-linux", "i486-slackware-linux",
--    "i686-montavista-linux", "i686-linux-android", "i586-linux-gnu"
-+    "i686-montavista-linux", "i686-linux-android", "i586-linux-gnu",
-+    "i386-pc-solaris2.11", "i386-pc-solaris2.12", "i386-pc-solaris2.13"
-   };
- 
-   static const char *const MIPSLibDirs[] = { "/lib" };
-@@ -1358,10 +1382,18 @@
- 
-   static const char *const SPARCv8LibDirs[] = { "/lib32", "/lib" };
-   static const char *const SPARCv8Triples[] = { "sparc-linux-gnu",
--                                                "sparcv8-linux-gnu" };
--  static const char *const SPARCv9LibDirs[] = { "/lib64", "/lib" };
-+                                                "sparcv8-linux-gnu",
-+                                                "sparc-sun-solaris2.11",
-+                                                "sparc-sun-solaris2.12",
-+                                                "sparc-sun-solaris2.13" };
-+
-+  static const char *const SPARCv9LibDirs[] = { "/lib64", "/lib/sparcv9",
-+    "/lib/64", "/lib" };
-   static const char *const SPARCv9Triples[] = { "sparc64-linux-gnu",
--                                                "sparcv9-linux-gnu" };
-+                                                "sparcv9-linux-gnu",
-+                                                "sparcv9-sun-solaris2.11",
-+                                                "sparcv9-sun-solaris2.12",
-+                                                "sparcv9-sun-solaris2.13" };
- 
-   static const char *const SystemZLibDirs[] = { "/lib64", "/lib" };
-   static const char *const SystemZTriples[] = {
-@@ -2649,16 +2681,703 @@
- 
- /// Solaris - Solaris tool chain which can call as(1) and ld(1) directly.
- 
-+const char *Solaris::MediatedGCCToolChainPath =
-+"/path/to/mediated/gcc/toolchain";
-+const bool Solaris::SupportsClangLibCPlusPlus = false;
-+
- Solaris::Solaris(const Driver &D, const llvm::Triple& Triple,
--                 const ArgList &Args)
--  : Generic_GCC(D, Triple, Args) {
-+                 const llvm::opt::ArgList &Args)
-+  : Generic_ELF(D, Triple, Args),
-+  UseGnuAs(true),
-+  UseGnuLd(false),
-+  UseGoldLd(false),
-+  UseSunLd(true),
-+  UseMediatedGCCToolChainPath(false),
-+  UseSpecifiedGCCToolChainPath(false),
-+  IsValid(false),
-+  GCCInstallDir("/usr/gcc/"),
-+  GCCMajorMinor(""),
-+  GCCMajorMinorMicro(""),
-+  GCCInternalLibDir(""),
-+  GCCInternalMultiLibDir(""),
-+  GCCIncludeDirs(),
-+  Assembler("/usr/gnu/bin/as"),
-+  Linker("/usr/bin/ld"),
-+  mtune(""),
-+  march(""),
-+  mcpu(""),
-+  ExtraOpts() {
-+    if (Arg *A = Args.getLastArg(options::OPT_gcc_toolchain)) {
-+      GCCInstallDir = A->getValue();
-+      if (!llvm::sys::fs::exists(GCCInstallDir))
-+        D.Diag(diag::err_drv_no_such_file) << GCCInstallDir;
-+      else {
-+        findSpecifiedGCCToolchain(GCCInstallDir.c_str(), Triple, Args);
- 
--  getProgramPaths().push_back(getDriver().getInstalledDir());
-+        if (!UseSpecifiedGCCToolChainPath) {
-+          D.Diag(diag::err_drv_unsupported_rtlib_for_platform)
-+            << GCCInstallDir << Triple.getTriple();
-+        } else {
-+          findGCCIncludeDirs(Triple, Args);
-+          findGCCInternalLibDir(Triple, Args);
-+        }
-+      }
-+    } else if (llvm::sys::fs::exists(Solaris::MediatedGCCToolChainPath)) {
-+      GCCInstallDir = Solaris::MediatedGCCToolChainPath;
-+      UseMediatedGCCToolChainPath = true;
-+    } else {
-+      findGCCMajorMinor();
-+      findGCCMajorMinorMicro(Triple);
-+      findGCCIncludeDirs(Triple, Args);
-+      findGCCInternalLibDir(Triple, Args);
-+    }
-+
-+    if (Arg *A = Args.getLastArg(options::OPT_fuse_ld_EQ)) {
-+      Linker = A->getValue();
-+      if (Linker == "bfd")
-+        Linker = "/usr/gnu/bin/ld";
-+      else if (Linker == "gold")
-+        Linker = "/usr/gnu/bin/ld.gold";
-+
-+      if ((Linker == "/usr/gnu/bin/ld") || (Linker == "/usr/gnu/bin/ld.bfd") ||
-+          (Linker == "/usr/bin/gld") || (Linker == "/usr/bin/gld.bfd")) {
-+        UseGnuLd = true;
-+        UseGoldLd = false;
-+        UseSunLd = false;
-+      } else if ((Linker == "/usr/gnu/bin/ld.gold") ||
-+                 (Linker == "/usr/bin/gld.gold") ||
-+                 (Linker == "/usr/bin/ld.gold")) {
-+        UseGnuLd = false;
-+        UseSunLd = false;
-+        UseGoldLd = true;
-+      }
-+    }
-+
-+    if (Arg *A = Args.getLastArg(options::OPT_fuse_as_EQ)) {
-+      Assembler = A->getValue();
-+      if (Assembler == "llvm")
-+        UseGnuAs = false;
-+      else if ((Assembler == "/usr/gnu/bin/as") ||
-+               (Assembler == "/usr/bin/gas"))
-+        UseGnuAs = true;
-+      else if (Assembler == "gas") {
-+        Assembler = "/usr/gnu/bin/as";
-+        UseGnuAs = true;
-+      } else if ((Assembler == "/usr/bin/as") || (Assembler == "sun") ||
-+                 (Assembler == "solaris"))
-+        D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
-+    }
-+
-+    getProgramPaths().push_back(GCCInstallDir);
-   if (getDriver().getInstalledDir() != getDriver().Dir)
-     getProgramPaths().push_back(getDriver().Dir);
- 
-+    llvm::Triple::ArchType Arch = Triple.getArch();
-+
-+    switch (Arch) {
-+    case llvm::Triple::x86:
-+      getFilePaths().push_back(getDriver().Dir + "/../lib");
-+      getFilePaths().push_back("/usr/lib");
-+      march = mtune = "i686";
-+      break;
-+    case llvm::Triple::sparc:
-+      getFilePaths().push_back(getDriver().Dir + "/../lib");
-+      getFilePaths().push_back("/usr/lib");
-+      mcpu = "ultrasparc";
-+      mtune = "ultrasparc";
-+      march = "v8plusa";
-+      break;
-+    case llvm::Triple::x86_64:
-+      getFilePaths().push_back(getDriver().Dir + "/../lib/amd64");
-+      getFilePaths().push_back("/usr/lib/amd64");
-+      march = mtune = "opteron";
-+      break;
-+    case llvm::Triple::sparcv9:
-+      getFilePaths().push_back(getDriver().Dir + "/../lib/sparcv9");
-+      getFilePaths().push_back("/usr/lib/sparcv9");
-+      mcpu = "ultrasparc";
-+      mtune = "ultrasparc";
-+      march = "v9a";
-+      break;
-+    default:
-   getFilePaths().push_back(getDriver().Dir + "/../lib");
-   getFilePaths().push_back("/usr/lib");
-+      break;
-+    }
-+
-+    validate();
-+
-+    if (Args.hasArg(options::OPT_v))
-+      this->print(llvm::errs());
-+}
-+
-+std::string Solaris::computeSysRoot() const {
-+  if (!getDriver().SysRoot.empty())
-+    return getDriver().SysRoot;
-+
-+  return std::string("/");
-+}
-+
-+bool Solaris::addLibStdCXXIncludePaths(Twine Base, Twine Suffix,
-+                                       StringRef GCCTriple,
-+                                       StringRef GCCMultiarchTriple,
-+                                       StringRef TargetMultiarchTriple,
-+                                       Twine IncludeSuffix,
-+                                       const llvm::opt::ArgList &DriverArgs,
-+                                       llvm::opt::ArgStringList &CC1Args) const {
-+  if (!llvm::sys::fs::exists(Base + Suffix))
-+        return false;
-+
-+  addSystemInclude(DriverArgs, CC1Args, Base);
-+  addSystemInclude(DriverArgs, CC1Args, Base + Suffix);
-+
-+  if ((GCCMultiarchTriple.empty() && TargetMultiarchTriple.empty()) ||
-+      llvm::sys::fs::exists(Base + Suffix + "/" + GCCTriple + IncludeSuffix)) {
-+    addSystemInclude(DriverArgs,
-+                     CC1Args, Base + Suffix + "/" + GCCTriple + IncludeSuffix);
-+  } else {
-+    addSystemInclude(DriverArgs, CC1Args,
-+                     Base + "/" + GCCMultiarchTriple + Suffix + IncludeSuffix);
-+    addSystemInclude(DriverArgs, CC1Args,
-+                     Base + "/" + TargetMultiarchTriple + Suffix);
-+  }
-+
-+  addSystemInclude(DriverArgs, CC1Args, Base + "/backward");
-+  addSystemInclude(DriverArgs, CC1Args, Base + Suffix + "/backward");
-+  return true;
-+}
-+
-+void Solaris::AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs,
-+                                           llvm::opt::ArgStringList &CC1Args) const {
-+  if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
-+      DriverArgs.hasArg(options::OPT_nostdincxx))
-+    return;
-+
-+  const Driver &D = getDriver();
-+
-+  // Check for Clang libc++
-+  if (GetCXXStdlibType(DriverArgs) == ToolChain::CST_Libcxx) {
-+    if (!Solaris::SupportsClangLibCPlusPlus) {
-+      D.Diag(diag::err_drv_invalid_stdlib_name) << "libc++";
-+      return;
-+    }
-+
-+    StringRef IncludePath = "/usr/include/libc++/v1";
-+    if (!llvm::sys::fs::exists(IncludePath)) {
-+      D.Diag(diag::err_drv_no_such_file) << IncludePath;
-+      return;
-+    }
-+
-+    addSystemInclude(DriverArgs, CC1Args, IncludePath);
-+    return;
-+  }
-+
-+  for (std::vector<std::string>::const_iterator B =
-+      getGCCIncludeDirs().begin(), E = getGCCIncludeDirs().end();
-+      B != E; ++B) {
-+    llvm::Twine IncludePath((*B));
-+    addSystemInclude(DriverArgs, CC1Args, IncludePath);
-+  }
-+}
-+
-+void Solaris::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
-+                                        ArgStringList &CC1Args) const {
-+  const Driver &D = getDriver();
-+
-+  if (DriverArgs.hasArg(options::OPT_nostdinc))
-+    return;
-+
-+  std::string SysRoot = computeSysRoot();
-+
-+  if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
-+    SmallString<PATH_MAX> P(D.ResourceDir);
-+    llvm::sys::path::append(P, "/include");
-+    addSystemInclude(DriverArgs, CC1Args, P.str());
-+  }
-+
-+  if (DriverArgs.hasArg(options::OPT_nostdlibinc))
-+    return;
-+
-+  StringRef CIncludeDirs(C_INCLUDE_DIRS);
-+  if (CIncludeDirs != "") {
-+    SmallVector<StringRef, 5> dirs;
-+    CIncludeDirs.split(dirs, ":");
-+    for (SmallVectorImpl<StringRef>::iterator I = dirs.begin(), E = dirs.end();
-+         I != E; ++I) {
-+      StringRef Prefix =
-+        llvm::sys::path::is_absolute(*I) ? StringRef(SysRoot) : "";
-+      addExternCSystemInclude(DriverArgs, CC1Args, Prefix + *I);
-+    }
-+  }
-+
-+  addExternCSystemInclude(DriverArgs, CC1Args, "/usr/include");
-+}
-+
-+void Solaris::addClangTargetOptions(const ArgList &DriverArgs,
-+                                    ArgStringList &CC1Args) const {
-+  const llvm::Triple& TT = getTriple();
-+  llvm::Triple::ArchType Arch = TT.getArch();
-+
-+  if (Arg *A = DriverArgs.getLastArg(options::OPT_mtune_EQ)) {
-+    StringRef V = A->getValue();
-+    if (!V.empty())
-+      mtune = V.str();
-+
-+    // FIXME: Impplement SPARC target features.
-+    CC1Args.push_back(DriverArgs.MakeArgString("-target-feature"));
-+    if (Arch == llvm::Triple::sparc || Arch == llvm::Triple::sparcv9) {
-+      std::string S = "mtune=";
-+      S += mtune;
-+      CC1Args.push_back(DriverArgs.MakeArgString(S.c_str()));
-+    } else {
-+      CC1Args.push_back(DriverArgs.MakeArgString(mtune.c_str()));
-+    }
-+  }
-+
-+  if (Arg *A = DriverArgs.getLastArg(options::OPT_march_EQ)) {
-+    StringRef V = A->getValue();
-+    if (!V.empty())
-+      march = V.str();
-+
-+    CC1Args.push_back(DriverArgs.MakeArgString("-target-feature"));
-+
-+    if ((Arch == llvm::Triple::sparc) || (Arch == llvm::Triple::sparcv9)) {
-+      std::string S = "march=";
-+      S += mtune;
-+      CC1Args.push_back(DriverArgs.MakeArgString(S.c_str()));
-+    } else {
-+      CC1Args.push_back(DriverArgs.MakeArgString(march.c_str()));
-+    }
-+  }
-+
-+  if (Arch == llvm::Triple::sparc || Arch == llvm::Triple::sparcv9) {
-+    if (Arg *A = DriverArgs.getLastArg(options::OPT_mcpu_EQ)) {
-+      StringRef V = A->getValue();
-+      if (!V.empty())
-+        mcpu = V.str();
-+      else
-+        mcpu = "ultrasparc";
-+    }
-+
-+    CC1Args.push_back(DriverArgs.MakeArgString("-target-feature"));
-+    std::string S = "mcpu=";
-+    S += mcpu;
-+    CC1Args.push_back(DriverArgs.MakeArgString(S.c_str()));
-+
-+    if (Arg *A = DriverArgs.getLastArg(options::OPT_mvis)) {
-+      CC1Args.push_back(DriverArgs.MakeArgString("-target-feature"));
-+      CC1Args.push_back(DriverArgs.MakeArgString("vis"));
-+    } else if (Arg *A = DriverArgs.getLastArg(options::OPT_mvis2)) {
-+      CC1Args.push_back(DriverArgs.MakeArgString("-target-feature"));
-+      CC1Args.push_back(DriverArgs.MakeArgString("vis2"));
-+    } else if (Arg *A = DriverArgs.getLastArg(options::OPT_mvis3)) {
-+      CC1Args.push_back(DriverArgs.MakeArgString("-target-feature"));
-+      CC1Args.push_back(DriverArgs.MakeArgString("vis3"));
-+    }
-+  }
-+}
-+
-+void Solaris::findGCCMajorMinor() const {
-+  // FIXME: Add 5.2 after testing the ABI.
-+  static const char* const GCCMM[] = { "4.8", "4.9" };
-+
-+  const char* P;
-+  std::string Path;
-+
-+  if (UseMediatedGCCToolChainPath) {
-+    // FIXME: IMPLEMENT.
-+    // Needs spec.
-+  }
-+
-+  Path.reserve(std::string::size_type(PATH_MAX));
-+
-+  for (int I = (llvm::array_lengthof(GCCMM) - 1); I >= 0; --I) {
-+    if ((P = GCCMM[I]) != NULL) {
-+      Path = GCCInstallDir;
-+      Path.append(P);
-+      Path.append("/");
-+
-+      if (llvm::sys::fs::exists(Path.c_str())) {
-+        GCCMajorMinor = P;
-+        break;
-+      }
-+    }
-+  }
-+}
-+
-+void Solaris::findGCCMajorMinorMicro(const llvm::Triple& T) const {
-+  // FIXME: Add 5.2.0 after testing the ABI.
-+  static const char* const GCCMMM[] = { "4.8.2", "4.8.5", "4.9.3" };
-+
-+  const char* P;
-+  std::string Path;
-+  std::string TripleString = llvm::sys::getDefaultTargetTriple();
-+  llvm::Triple::ArchType Arch = T.getArch();
-+
-+  if (UseMediatedGCCToolChainPath) {
-+    // FIXME: IMPLEMENT.
-+    // Needs spec.
-+  }
-+
-+  Path.reserve(std::string::size_type(PATH_MAX));
-+
-+  for (int I = (llvm::array_lengthof(GCCMMM) - 1); I >= 0; --I) {
-+    if ((P = GCCMMM[I]) != NULL) {
-+      if ((P[0] == GCCMajorMinor[0]) && (P[2] == GCCMajorMinor[2])) {
-+        Path = GCCInstallDir;
-+        Path.append("/");
-+        Path.append(GCCMajorMinor);
-+        Path.append("/lib/gcc/");
-+        Path.append(TripleString);
-+        Path.append("/");
-+        Path.append(P);
-+
-+        if (llvm::sys::fs::exists(Path.c_str())) {
-+          std::string Test;
-+          // Check if this is a real GCC installation and not just
-+          // an empty directory tree
-+          switch (Arch) {
-+              case llvm::Triple::x86:
-+              case llvm::Triple::sparc:
-+                Test = Path + "/crtbegin.o";
-+                break;
-+              case llvm::Triple::x86_64:
-+                Test = Path + "/amd64/crtbegin.o";
-+                break;
-+              case llvm::Triple::sparcv9:
-+                Test = Path + "/sparcv9/crtbegin.o";
-+                break;
-+              default:
-+                break;
-+          }
-+
-+          if (llvm::sys::fs::exists(Test.c_str())) {
-+            GCCMajorMinorMicro = P;
-+            break;
-+          }
-+        }
-+      }
-+    }
-+  }
-+}
-+
-+void Solaris::findSpecifiedGCCToolchain(const char *StartingPath,
-+                                        const llvm::Triple &Triple,
-+                                        const llvm::opt::ArgList &Args) const {
-+  DIR *TopLD = 0;
-+  DIR *LibLD = 0;
-+  DIR *GccLD = 0;
-+  DIR *TripleLD = 0;
-+  struct dirent *TopDE = 0;
-+  struct dirent *LibDE = 0;
-+  struct dirent *GccDE = 0;
-+  struct dirent *TripleDE = 0;
-+  std::string LibDir;
-+  std::string GccDir;
-+  std::string TripleDir;
-+  std::string TripleVersionDir;
-+  const char *DName;
-+
-+  assert(StartingPath && "Invalid GCC Toolchain starting search path!");
-+
-+  GCCMajorMinor = "";
-+  GCCMajorMinorMicro = "";
-+  UseSpecifiedGCCToolChainPath = false;
-+
-+  LibDir.reserve(std::string::size_type(PATH_MAX));
-+  GccDir.reserve(std::string::size_type(PATH_MAX));
-+  TripleDir.reserve(std::string::size_type(PATH_MAX));
-+  TripleVersionDir.reserve(std::string::size_type(PATH_MAX));
-+
-+  if (llvm::sys::fs::exists(StartingPath) &&
-+      llvm::sys::fs::is_directory(StartingPath)) {
-+    TopLD = opendir(StartingPath);
-+    assert(TopLD && "Cannot obtain a valid toplevel DIR handle!");
-+
-+    while ((TopDE = readdir(TopLD)) != NULL) {
-+      if (TopDE->d_name[0] == '.')
-+        continue;
-+
-+      DName = reinterpret_cast<const char*>(&TopDE->d_name[0]);
-+      if (std::strcmp(DName, "lib") == 0) {
-+        LibDir = StartingPath;
-+        LibDir.append("/");
-+        LibDir.append(DName);
-+
-+        if (!llvm::sys::fs::is_directory(LibDir.c_str()))
-+          continue;
-+
-+        LibLD = opendir(LibDir.c_str());
-+        assert(LibLD && "Could not obtain a valid lib DIR handle!");
-+
-+        while ((LibDE = readdir(LibLD)) != NULL) {
-+          if (LibDE->d_name[0] == '.')
-+            continue;
-+
-+          DName = reinterpret_cast<const char*>(&LibDE->d_name[0]);
-+          if (std::strcmp(DName, "gcc") == 0) {
-+            GccDir = LibDir;
-+            GccDir.append("/");
-+            GccDir.append(DName);
-+
-+            if (!llvm::sys::fs::is_directory(GccDir.c_str()))
-+              continue;
-+
-+            GccLD = opendir(GccDir.c_str());
-+            assert(GccLD && "Could not obtain a valid gcc DIR handle!");
-+
-+            while ((GccDE = readdir(GccLD)) != NULL) {
-+              if (GccDE->d_name[0] == '.')
-+                continue;
-+
-+              DName = reinterpret_cast<const char*>(&GccDE->d_name[0]);
-+              TripleDir = GccDir;
-+              TripleDir.append("/");
-+              TripleDir.append(DName);
-+
-+              if (!llvm::sys::fs::is_directory(TripleDir.c_str()))
-+                continue;
-+
-+              if ((std::strncmp(DName, "sparc", 5) == 0) ||
-+                  (std::strncmp(DName, "i386", 4) == 0) ||
-+                  (std::strncmp(DName, "sparcv9", 7) == 0) ||
-+                  (std::strncmp(DName, "x86_64", 6) == 0)) {
-+                TripleLD = opendir(TripleDir.c_str());
-+                assert(TripleLD &&
-+                       "Could not obtain a valid Triple DIR handle!");
-+
-+                while ((TripleDE = readdir(TripleLD)) != NULL) {
-+                  if (TripleDE->d_name[0] == '.')
-+                    continue;
-+
-+                  DName = reinterpret_cast<const char*>(&TripleDE->d_name[0]);
-+                  TripleVersionDir = TripleDir;
-+                  TripleVersionDir.append("/");
-+                  TripleVersionDir.append(DName);
-+
-+                  if (!llvm::sys::fs::is_directory(TripleVersionDir.c_str()))
-+                    continue;
-+
-+                  if ((std::isdigit(DName[0])) && (DName[1] == '.') &&
-+                      (std::isdigit(DName[2])) && (DName[3] == '.') &&
-+                      (std::isdigit(DName[4])) && (DName[5] == '\0')) {
-+                    GCCMajorMinorMicro = DName;
-+                    GCCMajorMinor = GCCMajorMinorMicro.substr(0, 3);
-+                    UseSpecifiedGCCToolChainPath = true;
-+                    goto done;
-+                  }
-+                }
-+              }
-+            }
-+          }
-+        }
-+      }
-+    }
-+  }
-+
-+done:
-+  if (TripleLD) {
-+    rewinddir(TripleLD);
-+    closedir(TripleLD);
-+  }
-+
-+  if (GccLD) {
-+    rewinddir(GccLD);
-+    closedir(GccLD);
-+  }
-+
-+  if (LibLD) {
-+    rewinddir(LibLD);
-+    closedir(LibLD);
-+  }
-+
-+  if (TopLD) {
-+    rewinddir(TopLD);
-+    closedir(TopLD);
-+  }
-+}
-+
-+
-+
-+void Solaris::findGCCIncludeDirs(const llvm::Triple &Triple,
-+                                 const llvm::opt::ArgList &Args) const {
-+  std::string GCCInstallPath;
-+  if (UseSpecifiedGCCToolChainPath)
-+    GCCInstallPath = GCCInstallDir;
-+  else if (UseMediatedGCCToolChainPath)
-+    GCCInstallPath = Solaris::MediatedGCCToolChainPath;
-+  else
-+    GCCInstallPath = GCCInstallDir + GCCMajorMinor;
-+
-+  std::string GCCIncludeDir =
-+    GCCInstallPath + "/include/c++/" + GCCMajorMinorMicro;
-+  GCCIncludeDirs.push_back(GCCIncludeDir);
-+
-+  llvm::Triple::ArchType Arch = Triple.getArch();
-+  GCCIncludeDir += "/";
-+
-+  switch (Arch) {
-+    case llvm::Triple::x86:
-+      GCCIncludeDir += Triple.getTriple();
-+      if (Arg *A = Args.getLastArg(options::OPT_m64))
-+        GCCIncludeDir += "/amd64";
-+      break;
-+    case llvm::Triple::sparc:
-+      GCCIncludeDir += Triple.getTriple();
-+      if (Arg *A = Args.getLastArg(options::OPT_m64))
-+        GCCIncludeDir += "/sparcv9";
-+      break;
-+    case llvm::Triple::x86_64:
-+      GCCIncludeDir += "i386-pc-";
-+      GCCIncludeDir += Triple.getOSName();
-+      if (Arg *A = Args.getLastArg(options::OPT_m64))
-+        GCCIncludeDir += "/amd64";
-+      break;
-+    case llvm::Triple::sparcv9:
-+      GCCIncludeDir += "sparc-sun-";
-+      GCCIncludeDir += Triple.getOSName();
-+      if (Arg *A = Args.getLastArg(options::OPT_m64))
-+        GCCIncludeDir += "/sparcv9";
-+      break;
-+    default:
-+      getDriver().Diag(diag::err_target_unsupported_arch)
-+        << Triple.getArchName() << Triple.getTriple();
-+      break;
-+  }
-+
-+  GCCIncludeDirs.push_back(GCCIncludeDir);
-+
-+  GCCIncludeDir = GCCInstallPath + "/include/c++/" +
-+    GCCMajorMinorMicro + "/backward";
-+
-+  GCCIncludeDirs.push_back(GCCIncludeDir);
-+}
-+
-+void Solaris::findGCCInternalLibDir(const llvm::Triple &Triple,
-+                                    const llvm::opt::ArgList &Args) const {
-+  std::string GCCInstallPath;
-+  if (UseSpecifiedGCCToolChainPath)
-+    GCCInstallPath = GCCInstallDir;
-+  else if (UseMediatedGCCToolChainPath)
-+    GCCInstallPath = Solaris::MediatedGCCToolChainPath;
-+  else
-+    GCCInstallPath = GCCInstallDir + GCCMajorMinor;
-+
-+  GCCInternalLibDir = GCCInstallPath + "/lib/gcc/";
-+
-+  llvm::Triple::ArchType Arch = Triple.getArch();
-+
-+  switch (Arch) {
-+    case llvm::Triple::x86:
-+      GCCInternalLibDir += Triple.getTriple();
-+      GCCInternalLibDir += "/";
-+      GCCInternalLibDir += GCCMajorMinorMicro;
-+      if (Arg *A = Args.getLastArg(options::OPT_m64)) {
-+        GCCInternalMultiLibDir = GCCInternalLibDir;
-+        GCCInternalLibDir += "/amd64";
-+      } else if (Arg *A = Args.getLastArg(options::OPT_m32)) {
-+        GCCInternalMultiLibDir = GCCInternalLibDir;
-+        GCCInternalMultiLibDir += "/amd64";
-+      } else {
-+        GCCInternalMultiLibDir = GCCInternalLibDir;
-+        GCCInternalMultiLibDir += "/amd64";
-+      }
-+
-+      break;
-+    case llvm::Triple::sparc:
-+      GCCInternalLibDir += Triple.getTriple();
-+      GCCInternalLibDir += "/";
-+      GCCInternalLibDir += GCCMajorMinorMicro;
-+      if (Arg *A = Args.getLastArg(options::OPT_m64)) {
-+        GCCInternalMultiLibDir = GCCInternalLibDir;
-+        GCCInternalLibDir += "/sparcv9";
-+      } else if (Arg *A = Args.getLastArg(options::OPT_m32)) {
-+        GCCInternalMultiLibDir = GCCInternalLibDir;
-+        GCCInternalMultiLibDir += "/sparcv9";
-+      } else {
-+        GCCInternalMultiLibDir = GCCInternalLibDir;
-+        GCCInternalMultiLibDir += "/sparcv9";
-+      }
-+      break;
-+    case llvm::Triple::x86_64:
-+      GCCInternalLibDir += "i386-pc-";
-+      GCCInternalLibDir += Triple.getOSName();
-+      GCCInternalLibDir += "/";
-+      GCCInternalLibDir += GCCMajorMinorMicro;
-+      GCCInternalMultiLibDir = GCCInternalLibDir;
-+      if (Arg *A = Args.getLastArg(options::OPT_m64))
-+        GCCInternalLibDir += "/amd64";
-+      else if (Arg *A = Args.getLastArg(options::OPT_m32))
-+        GCCInternalMultiLibDir += "/amd64";
-+      else
-+        GCCInternalLibDir += "/amd64";
-+      break;
-+    case llvm::Triple::sparcv9:
-+      GCCInternalLibDir += "sparc-sun-";
-+      GCCInternalLibDir += Triple.getOSName();
-+      GCCInternalLibDir += "/";
-+      GCCInternalLibDir += GCCMajorMinorMicro;
-+      GCCInternalMultiLibDir = GCCInternalLibDir;
-+      if (Arg *A = Args.getLastArg(options::OPT_m64))
-+        GCCInternalLibDir += "/sparcv9";
-+      else if (Arg *A = Args.getLastArg(options::OPT_m32))
-+        GCCInternalMultiLibDir += "/sparcv9";
-+      else
-+        GCCInternalLibDir += "/sparcv9";
-+      break;
-+    default:
-+      getDriver().Diag(diag::err_target_unsupported_arch)
-+        << Triple.getArchName() << Triple.getTriple();
-+      break;
-+  }
-+}
-+
-+void Solaris::print(raw_ostream &OS) const {
-+  OS << "UseGnuAs: " << (UseGnuAs ? "true" : "false") << "\n";
-+  OS << "UseGnuLd: " << (UseGnuLd ? "true" : "false") << "\n";
-+  OS << "UseGoldLd: " << (UseGoldLd ? "true" : "false") << "\n";
-+  OS << "UseSunLd: " << (UseSunLd ? "true" : "false") << "\n";
-+  OS << "UseMediatedGCCToolChainPath: "
-+    << (UseMediatedGCCToolChainPath ? "true" : "false") << "\n";
-+  OS << "UseSpecifiedGCCToolChainPath: "
-+    << (UseSpecifiedGCCToolChainPath ? "true" : "false") << "\n";
-+  OS << "GCCInstallDir: " << GCCInstallDir.c_str() << "\n";
-+  OS << "GCCMajorMinor: " << GCCMajorMinor.c_str() << "\n";
-+  OS << "GCCMajorMinorMicro: " << GCCMajorMinorMicro.c_str() << "\n";
-+  OS << "GCCInternalLibDir: " << GCCInternalLibDir.c_str() << "\n";
-+  OS << "GCCInternalMultiLibDir: " << GCCInternalMultiLibDir.c_str() << "\n";
-+  OS << "MediatedGCCToolChainPath: " << MediatedGCCToolChainPath << "\n";
-+  OS << "GCCIncludeDirs: ";
-+
-+  if (GCCIncludeDirs.size()) {
-+    std::string IncludePath;
-+    for (std::vector<std::string>::const_iterator B = GCCIncludeDirs.begin(),
-+        E = GCCIncludeDirs.end(); B != E; ++B) {
-+      IncludePath = "-I";
-+      IncludePath += (*B);
-+      OS << IncludePath.c_str() << " ";
-+    }
-+
-+    OS << "\n";
-+  }
-+
-+  OS << "Assembler: " << Assembler.c_str() << "\n";
-+  OS << "Linker: " << Linker.c_str() << "\n";
-+  OS << "mtune: " << mtune.c_str() << "\n";
-+  OS << "march: " << march.c_str() << "\n";
-+  OS << "mcpu: " << mcpu.c_str() << "\n";
-+
-+  if (ExtraOpts.size()) {
-+    OS << "ExtraOpts: ";
-+    for (std::vector<std::string>::const_iterator B = ExtraOpts.begin(),
-+        E = ExtraOpts.end(); B != E; ++B) {
-+      OS << (*B).c_str() << " ";
-+    }
-+
-+    OS << "\n";
-+  }
-+
-+  OS << "Valid: " << (IsValid ? "true" : "false") << "\n";
- }
- 
- Tool *Solaris::buildAssembler() const {
-@@ -2669,6 +3388,21 @@
-   return new tools::solaris::Link(*this);
- }
- 
-+void Solaris::validate() {
-+  IsValid = llvm::sys::fs::exists(GCCInstallDir.c_str());
-+  if (!IsValid) return;
-+  IsValid = llvm::sys::fs::exists(GCCInternalLibDir.c_str());
-+  if (!IsValid) return;
-+  IsValid = llvm::sys::fs::exists(GCCInternalMultiLibDir.c_str());
-+  if (!IsValid) return;
-+
-+  for (std::vector<std::string>::const_iterator B = GCCIncludeDirs.begin(),
-+      E = GCCIncludeDirs.end(); B != E; ++B) {
-+    IsValid = llvm::sys::fs::exists((*B).c_str());
-+    if (!IsValid) return;
-+  }
-+}
-+
- /// Distribution (very bare-bones at the moment).
- 
- enum Distro {
-@@ -2696,6 +3430,27 @@
-   UbuntuRaring,
-   UbuntuSaucy,
-   UbuntuTrusty,
-+  Solaris_11,
-+  Solaris_11_1,
-+  Solaris_11_2,
-+  Solaris_11_3,
-+  Solaris_11_4,
-+  Solaris_11_5,
-+  Solaris_11_6,
-+  Solaris_11_7,
-+  Solaris_11_8,
-+  Solaris_11_9,
-+  Solaris_12,
-+  Solaris_12_1,
-+  Solaris_12_2,
-+  Solaris_12_3,
-+  Solaris_12_4,
-+  Solaris_12_5,
-+  Solaris_12_6,
-+  Solaris_12_7,
-+  Solaris_12_8,
-+  Solaris_12_9,
-+  Solaris_13,
-   UnknownDistro
- };
- 
-@@ -2715,6 +3470,10 @@
-   return Distro >= UbuntuHardy && Distro <= UbuntuTrusty;
- }
- 
-+static bool IsSolaris(enum Distro Distro) {
-+  return Distro >= Solaris_11 && Distro <= Solaris_13;
-+}
-+
- static Distro DetectDistro(llvm::Triple::ArchType Arch) {
-   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> File =
-       llvm::MemoryBuffer::getFile("/etc/lsb-release");
-@@ -2774,6 +3533,59 @@
-     return UnknownDistro;
-   }
- 
-+  File = llvm::MemoryBuffer::getFile("/etc/release");
-+  if (File) {
-+    StringRef Data = File.get()->getBuffer();
-+    SmallVector<StringRef, 8> Lines;
-+    Data.split(Lines, "\n");
-+    for (unsigned I = 0, S = Lines.size(); I != S; ++I) {
-+      if (Lines[I].find("Oracle Solaris") != std::string::npos) {
-+        if (Lines[I].find("Solaris 11.0") != std::string::npos)
-+          return Solaris_11;
-+        else if (Lines[I].find("Solaris 11.1") != std::string::npos)
-+          return Solaris_11_1;
-+        else if (Lines[I].find("Solaris 11.2") != std::string::npos)
-+          return Solaris_11_2;
-+        else if (Lines[I].find("Solaris 11.3") != std::string::npos)
-+          return Solaris_11_3;
-+        else if (Lines[I].find("Solaris 11.4") != std::string::npos)
-+          return Solaris_11_4;
-+        else if (Lines[I].find("Solaris 11.5") != std::string::npos)
-+          return Solaris_11_5;
-+        else if (Lines[I].find("Solaris 11.6") != std::string::npos)
-+          return Solaris_11_6;
-+        else if (Lines[I].find("Solaris 11.7") != std::string::npos)
-+          return Solaris_11_7;
-+        else if (Lines[I].find("Solaris 11.8") != std::string::npos)
-+          return Solaris_11_8;
-+        else if (Lines[I].find("Solaris 11.9") != std::string::npos)
-+          return Solaris_11_9;
-+        else if (Lines[I].find("Solaris 12.0") != std::string::npos)
-+          return Solaris_12;
-+        else if (Lines[I].find("Solaris 12.1") != std::string::npos)
-+          return Solaris_12_1;
-+        else if (Lines[I].find("Solaris 12.2") != std::string::npos)
-+          return Solaris_12_2;
-+        else if (Lines[I].find("Solaris 12.3") != std::string::npos)
-+          return Solaris_12_3;
-+        else if (Lines[I].find("Solaris 12.4") != std::string::npos)
-+          return Solaris_12_4;
-+        else if (Lines[I].find("Solaris 12.5") != std::string::npos)
-+          return Solaris_12_5;
-+        else if (Lines[I].find("Solaris 12.6") != std::string::npos)
-+          return Solaris_12_6;
-+        else if (Lines[I].find("Solaris 12.7") != std::string::npos)
-+          return Solaris_12_7;
-+        else if (Lines[I].find("Solaris 12.8") != std::string::npos)
-+          return Solaris_12_8;
-+        else if (Lines[I].find("Solaris 12.9") != std::string::npos)
-+          return Solaris_12_9;
-+      }
-+    }
-+
-+    return UnknownDistro;
-+  }
-+
-   if (llvm::sys::fs::exists("/etc/SuSE-release"))
-     return OpenSUSE;
- 
---- tools/llvm-shlib/Makefile	Sat Jul 18 11:44:45 2015
-+++ tools/llvm-shlib/Makefile	Thu Aug 20 23:40:28 2015
-@@ -74,6 +74,7 @@
-     LLVMLibsOptions := -Wl,-z -Wl,rescan -Wl,-z -Wl,allextract $(LLVMLibsOptions)
-     LLVMLibsOptions += -Wl,-h -Wl,lib$(LIBRARYNAME)$(SHLIBEXT)
-     LLVMLibsOptions += -Wl,-z -Wl,defaultextract -Wl,-z -Wl,defs
-+    LLVMLibsOptions += -lkstat
- endif
- 
- ifeq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW))
---- tools/clang/lib/Basic/Targets.cpp	2015-08-26 11:44:48.659904739 -0700
-+++ tools/clang/lib/Basic/Targets.cpp	2015-08-26 11:47:36.318310023 -0700
-@@ -530,28 +530,60 @@
- template<typename Target>
- class SolarisTargetInfo : public OSTargetInfo<Target> {
- protected:
--  void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
-+  virtual void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
-                     MacroBuilder &Builder) const override {
-     DefineStd(Builder, "sun", Opts);
-     DefineStd(Builder, "unix", Opts);
-     Builder.defineMacro("__ELF__");
-     Builder.defineMacro("__svr4__");
-     Builder.defineMacro("__SVR4");
--    // Solaris headers require _XOPEN_SOURCE to be set to 600 for C99 and
--    // newer, but to 500 for everything else.  feature_test.h has a check to
--    // ensure that you are not using C99 with an old version of X/Open or C89
--    // with a new version.
--    if (Opts.C99)
-+
-+    if (Opts.C99 || Opts.CPlusPlus11) {
-+      if (Opts.C99) {
-       Builder.defineMacro("_XOPEN_SOURCE", "600");
--    else
-+        Builder.defineMacro("_XPG6", "1");
-+      }
-+
-+      Builder.defineMacro("__STDC_VERSION__", "199901L");
-+      Builder.defineMacro("_STDC_C99", "1");
-+      Builder.defineMacro("__C99FEATURES__", "1");
-+    }
-+
-+    if (Opts.CPlusPlus11)
-+      Builder.defineMacro("__cplusplus", "201103L");
-+    else if (Opts.CPlusPlus14)
-+      Builder.defineMacro("__cplusplus", "201402L");
-+
-+    if (Opts.CPlusPlus11) {
-+      Builder.defineMacro("_STDC_C11", "1");
-+      Builder.defineMacro("_STDC_C11_BCI", "1");
-+      Builder.defineMacro("__XPG7_THREAD_MODEL__", "1");
-+      Builder.defineMacro("_XPG7", "1");
-+      Builder.defineMacro("_XOPEN_SOURCE", "700");
-+    } else if (Opts.C11 || Opts.CPlusPlus14) {
-+      Builder.defineMacro("__STDC_VERSION__", "201112L");
-+      Builder.defineMacro("_STDC_C11", "1");
-+      Builder.defineMacro("_STDC_C11_BCI", "1");
-+      Builder.defineMacro("__XPG7_THREAD_MODEL__", "1");
-+      Builder.defineMacro("_XPG7", "1");
-+      Builder.defineMacro("_XOPEN_SOURCE", "700");
-+    } else {
-       Builder.defineMacro("_XOPEN_SOURCE", "500");
--    if (Opts.CPlusPlus)
--      Builder.defineMacro("__C99FEATURES__");
-+      Builder.defineMacro("__STDC_VERSION__", "199409L");
-+      if (Opts.CPlusPlus && !Opts.CPlusPlus11 && !Opts.CPlusPlus14)
-+        Builder.defineMacro("__cplusplus", "199711L");
-+    }
-+
-+    if ((Triple.getArchName() == "i386") || (Triple.getArchName() == "sparc"))
-     Builder.defineMacro("_LARGEFILE_SOURCE");
-+    else if ((Triple.getArchName() == "x86_64") ||
-+             (Triple.getArchName() == "sparcv9"))
-     Builder.defineMacro("_LARGEFILE64_SOURCE");
--    Builder.defineMacro("__EXTENSIONS__");
-+
-+    Builder.defineMacro("__EXTENSIONS__", "1");
-     Builder.defineMacro("_REENTRANT");
-   }
-+
- public:
-   SolarisTargetInfo(const llvm::Triple &Triple) : OSTargetInfo<Target>(Triple) {
-     this->UserLabelPrefix = "";
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/014-solaris-clang-libclangLex.patch	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,74 @@
+# 17867434 clang crashed in LEXER
+# 3.9.X for upstream.
+--- tools/clang/include/clang/Lex/MacroArgs.h	2015-04-11 11:58:30.000000000 -0400
++++ tools/clang/include/clang/Lex/MacroArgs.h	2016-05-08 23:19:20.554431288 -0400
+@@ -15,13 +15,13 @@
+ #define LLVM_CLANG_LEX_MACROARGS_H
+ 
+ #include "clang/Basic/LLVM.h"
++#include "clang/Lex/Token.h"
+ #include "llvm/ADT/ArrayRef.h"
+ #include <vector>
+ 
+ namespace clang {
+   class MacroInfo;
+   class Preprocessor;
+-  class Token;
+   class SourceLocation;
+ 
+ /// MacroArgs - An instance of this class captures information about
+@@ -121,6 +121,9 @@
+   /// its freelist.
+   MacroArgs *deallocate();
+ };
++static_assert(llvm::AlignOf<MacroArgs>::Alignment >=
++                  llvm::AlignOf<Token>::Alignment,
++              "Alignment is insufficient for objects appended to MacroArgs");
+ 
+ }  // end namespace clang
+ 
+--- tools/clang/include/clang/Lex/MacroInfo.h	2015-10-22 00:59:52.000000000 -0400
++++ tools/clang/include/clang/Lex/MacroInfo.h	2016-05-08 23:19:20.554431288 -0400
+@@ -295,6 +295,10 @@
+   friend class Preprocessor;
+ };
+ 
++static_assert(llvm::AlignOf<MacroInfo>::Alignment >=
++              llvm::AlignOf<unsigned>::Alignment,
++              "Alignment is insufficient for objects appended to MacroInfo");
++
+ class DefMacroDirective;
+ 
+ /// \brief Encapsulates changes to the "macros namespace" (the location where
+@@ -315,16 +319,16 @@
+   SourceLocation Loc;
+ 
+   /// \brief MacroDirective kind.
+-  unsigned MDKind : 2;
++  unsigned MDKind;
+ 
+   /// \brief True if the macro directive was loaded from a PCH file.
+-  bool IsFromPCH : 1;
++  bool IsFromPCH;
+ 
+   // Used by VisibilityMacroDirective ----------------------------------------//
+ 
+   /// \brief Whether the macro has public visibility (when described in a
+   /// module).
+-  bool IsPublic : 1;
++  bool IsPublic;
+ 
+   MacroDirective(Kind K, SourceLocation Loc)
+       : Previous(nullptr), Loc(Loc), MDKind(K), IsFromPCH(false),
+@@ -556,6 +560,10 @@
+   unsigned getNumOverridingMacros() const { return NumOverriddenBy; }
+ };
+ 
++static_assert(llvm::AlignOf<ModuleMacro>::Alignment >=
++              llvm::AlignOf<ModuleMacro *>::Alignment,
++              "Alignment is insufficient for objects appended to ModuleMacro");
++
+ /// \brief A description of the current definition of a macro.
+ ///
+ /// The definition of a macro comprises a set of (at least one) defining
+
--- a/components/llvm/patches/015-llvm-clang-memory-corruption.patch	Thu Jul 28 16:15:45 2016 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,782 +0,0 @@
-# Memory corruption in LLVM.
-# https://llvm.org/bugs/show_bug.cgi?id=24607
---- include/llvm/ADT/DenseMap.h	2014-12-06 14:22:44.000000000 -0500
-+++ include/llvm/ADT/DenseMap.h	2015-08-25 21:45:36.712994054 -0400
-@@ -254,7 +254,7 @@
-   DenseMapBase() {}
- 
-   void destroyAll() {
--    if (getNumBuckets() == 0) // Nothing to do.
-+    if ((getNumBuckets() == 0) || empty()) // Nothing to do.
-       return;
- 
-     const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
---- include/llvm/IR/Attributes.h	2014-09-03 19:38:05.000000000 -0400
-+++ include/llvm/IR/Attributes.h	2015-08-25 11:24:38.160033797 -0400
-@@ -406,18 +406,27 @@
-   uint64_t Alignment;
-   uint64_t StackAlignment;
-   uint64_t DerefBytes;
-+
- public:
--  AttrBuilder() : Attrs(0), Alignment(0), StackAlignment(0), DerefBytes(0) {}
-+  AttrBuilder() : Attrs(0), TargetDepAttrs(), Alignment(0),
-+  StackAlignment(0), DerefBytes(0) {}
-+
-   explicit AttrBuilder(uint64_t Val)
--    : Attrs(0), Alignment(0), StackAlignment(0), DerefBytes(0) {
-+    : Attrs(0), TargetDepAttrs(), Alignment(0),
-+    StackAlignment(0), DerefBytes(0) {
-     addRawValue(Val);
-   }
-+
-   AttrBuilder(const Attribute &A)
--    : Attrs(0), Alignment(0), StackAlignment(0), DerefBytes(0) {
-+    : Attrs(0), TargetDepAttrs(), Alignment(0), StackAlignment(0),
-+    DerefBytes (0) {
-     addAttribute(A);
-   }
-+
-   AttrBuilder(AttributeSet AS, unsigned Idx);
- 
-+  ~AttrBuilder() { }
-+
-   void clear();
- 
-   /// \brief Add an attribute to the builder.
---- include/llvm/IR/Metadata.h	2015-02-08 19:35:35.000000000 -0800
-+++ include/llvm/IR/Metadata.h	2015-08-26 21:27:54.937575563 -0700
-@@ -24,6 +24,7 @@
- #include "llvm/IR/MetadataTracking.h"
- #include "llvm/IR/Value.h"
- #include "llvm/Support/ErrorHandling.h"
-+#include "llvm/Support/raw_ostream.h"
- #include <type_traits>
- 
- namespace llvm {
-@@ -42,13 +43,15 @@
- /// This is a root class for typeless data in the IR.
- class Metadata {
-   friend class ReplaceableMetadataImpl;
-+  friend class MDNode;
- 
-   /// \brief RTTI.
-   const unsigned char SubclassID;
- 
- protected:
-   /// \brief Storage flag for non-uniqued, otherwise unowned, metadata.
--  bool IsDistinctInContext : 1;
-+  bool IsDistinctInContext;
-+
-   // TODO: expose remaining bits to subclasses.
- 
-   unsigned short SubclassData16;
-@@ -149,7 +152,7 @@
-   SmallDenseMap<void *, std::pair<OwnerTy, uint64_t>, 4> UseMap;
- 
- public:
--  ReplaceableMetadataImpl() : NextIndex(0) {}
-+  ReplaceableMetadataImpl() : NextIndex(0), UseMap() {}
-   ~ReplaceableMetadataImpl() {
-     assert(UseMap.empty() && "Cannot destroy in-use replaceable metadata");
-   }
-@@ -583,9 +586,11 @@
- //===----------------------------------------------------------------------===//
- /// \brief Tuple of metadata.
- class MDNode : public Metadata {
-+  friend class MDNodeFwdDecl;
-+  friend class MDTuple;
-+
-   MDNode(const MDNode &) LLVM_DELETED_FUNCTION;
-   void operator=(const MDNode &) LLVM_DELETED_FUNCTION;
--  void *operator new(size_t) LLVM_DELETED_FUNCTION;
- 
-   LLVMContext &Context;
-   unsigned NumOperands;
-@@ -593,17 +598,21 @@
- protected:
-   unsigned MDNodeSubclassData;
- 
--  void *operator new(size_t Size, unsigned NumOps);
--  void operator delete(void *Mem);
-+  static void *operator new(size_t Size, unsigned NumOps) throw();
-+  static void operator delete(void *Mem) throw();
- 
-   /// \brief Required by std, but never called.
--  void operator delete(void *, unsigned) {
--    llvm_unreachable("Constructor throws?");
-+  static void operator delete(void *, unsigned) {
-+    llvm::errs() << __PRETTY_FUNCTION__
-+      << ": This should never be called!\n";
-+    abort();
-   }
- 
-   /// \brief Required by std, but never called.
--  void operator delete(void *, unsigned, bool) {
--    llvm_unreachable("Constructor throws?");
-+  static void operator delete(void *, unsigned, bool) {
-+    llvm::errs() << __PRETTY_FUNCTION__
-+      << ": This should never be called!\n";
-+    abort();
-   }
- 
-   MDNode(LLVMContext &Context, unsigned ID, ArrayRef<Metadata *> MDs);
-@@ -715,6 +724,8 @@
- class UniquableMDNode : public MDNode {
-   friend class ReplaceableMetadataImpl;
-   friend class MDNode;
-+  friend class MDTuple;
-+  friend class MDLocation;
-   friend class LLVMContextImpl;
- 
-   /// \brief Support RAUW as long as one of its arguments is replaceable.
-@@ -796,10 +807,14 @@
-   static MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
-     return getImpl(Context, MDs, /* ShouldCreate */ true);
-   }
-+
-   static MDTuple *getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
-     return getImpl(Context, MDs, /* ShouldCreate */ false);
-   }
- 
-+  void *operator new(size_t Size, unsigned NumOps) throw();
-+  void operator delete(void *Mem) throw();
-+
-   /// \brief Return a distinct node.
-   ///
-   /// Return a distinct node -- i.e., a node that is not uniqued.
-@@ -847,6 +862,9 @@
-   void replaceOperandWith(unsigned I, Metadata *New) LLVM_DELETED_FUNCTION;
- 
- public:
-+  void *operator new(size_t Size, unsigned NumOps) throw();
-+  void operator delete(void* Mem) throw();
-+
-   static MDLocation *get(LLVMContext &Context, unsigned Line, unsigned Column,
-                          Metadata *Scope, Metadata *InlinedAt = nullptr) {
-     return getImpl(Context, Line, Column, Scope, InlinedAt,
-@@ -885,18 +903,18 @@
- /// Forward declaration of metadata, in the form of a basic tuple.  Unlike \a
- /// MDTuple, this class has full support for RAUW, is not owned, is not
- /// uniqued, and is suitable for forward references.
--class MDNodeFwdDecl : public MDNode, ReplaceableMetadataImpl {
-+class MDNodeFwdDecl : public MDNode, public ReplaceableMetadataImpl {
-   friend class Metadata;
-   friend class ReplaceableMetadataImpl;
- 
-   MDNodeFwdDecl(LLVMContext &C, ArrayRef<Metadata *> Vals)
--      : MDNode(C, MDNodeFwdDeclKind, Vals) {}
-+  : MDNode(C, MDNodeFwdDeclKind, Vals), ReplaceableMetadataImpl() {}
- 
- public:
-   ~MDNodeFwdDecl() { dropAllReferences(); }
- 
--  // MSVC doesn't see the alternative: "using MDNode::operator delete".
--  void operator delete(void *Mem) { MDNode::operator delete(Mem); }
-+  void *operator new(size_t Size, unsigned NumOps) throw();
-+  void operator delete(void *Mem) throw();
- 
-   static MDNodeFwdDecl *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
-     return new (MDs.size()) MDNodeFwdDecl(Context, MDs);
---- lib/IR/Attributes.cpp	2014-09-03 19:38:05.000000000 -0400
-+++ lib/IR/Attributes.cpp	2015-08-26 00:21:40.551873740 -0400
-@@ -1004,7 +1004,8 @@
- //===----------------------------------------------------------------------===//
- 
- AttrBuilder::AttrBuilder(AttributeSet AS, unsigned Index)
--  : Attrs(0), Alignment(0), StackAlignment(0), DerefBytes(0) {
-+  : Attrs(0), TargetDepAttrs(), Alignment(0),
-+  StackAlignment(0), DerefBytes(0) {
-   AttributeSetImpl *pImpl = AS.pImpl;
-   if (!pImpl) return;
- 
-@@ -1052,7 +1053,9 @@
- }
- 
- AttrBuilder &AttrBuilder::addAttribute(StringRef A, StringRef V) {
--  TargetDepAttrs[A] = V;
-+  std::string AS = A.str();
-+  std::string VS = V.str();
-+  TargetDepAttrs[AS] = VS;
-   return *this;
- }
- 
-@@ -1094,8 +1097,9 @@
-         DerefBytes = 0;
-     } else {
-       assert(Attr.isStringAttribute() && "Invalid attribute type!");
--      std::map<std::string, std::string>::iterator
--        Iter = TargetDepAttrs.find(Attr.getKindAsString());
-+      std::string AS = Attr.getKindAsString().str();
-+      std::map<std::string, std::string>::iterator Iter =
-+        TargetDepAttrs.find(AS);
-       if (Iter != TargetDepAttrs.end())
-         TargetDepAttrs.erase(Iter);
-     }
-@@ -1105,7 +1109,8 @@
- }
- 
- AttrBuilder &AttrBuilder::removeAttribute(StringRef A) {
--  std::map<std::string, std::string>::iterator I = TargetDepAttrs.find(A);
-+  std::map<std::string, std::string>::iterator I =
-+    TargetDepAttrs.find(A.str());
-   if (I != TargetDepAttrs.end())
-     TargetDepAttrs.erase(I);
-   return *this;
-@@ -1163,7 +1168,7 @@
- }
- 
- bool AttrBuilder::contains(StringRef A) const {
--  return TargetDepAttrs.find(A) != TargetDepAttrs.end();
-+  return TargetDepAttrs.find(A.str()) != TargetDepAttrs.end();
- }
- 
- bool AttrBuilder::hasAttributes() const {
-@@ -1188,7 +1193,8 @@
-         return true;
-     } else {
-       assert(Attr.isStringAttribute() && "Invalid attribute kind!");
--      return TargetDepAttrs.find(Attr.getKindAsString())!=TargetDepAttrs.end();
-+      std::string AS = Attr.getKindAsString().str();
-+      return TargetDepAttrs.find(AS) != TargetDepAttrs.end();
-     }
-   }
- 
---- lib/IR/Metadata.cpp	2015-02-08 19:35:35.000000000 -0800
-+++ lib/IR/Metadata.cpp	2015-08-28 23:18:08.062765258 -0700
-@@ -379,24 +379,84 @@
- // MDNode implementation.
- //
- 
--void *MDNode::operator new(size_t Size, unsigned NumOps) {
--  void *Ptr = ::operator new(Size + NumOps * sizeof(MDOperand));
--  MDOperand *O = static_cast<MDOperand *>(Ptr);
--  for (MDOperand *E = O + NumOps; O != E; ++O)
--    (void)new (O) MDOperand;
--  return O;
--}
-+void *MDNode::operator new(size_t Size, unsigned NumOps) throw() {
-+  assert((Size >= sizeof(MDNode)) && "Insufficient size to operator new!");
-+
-+  // MDNode wants to construct its ancillary MDOperands ** BEFORE **
-+  // itself. 
-+  //
-+  // Allocate extra space for an uintptr_t at the beginning of the
-+  // buffer.  This uintptr_t is where we will store the address of
-+  // the memory-aligned storage buffer. It will be plasced immediately
-+  // after the last MDOperand.
-+  // This address will be computed by the matching operator delete.
-+  // The total amount of space allocated must include the Size
-+  // parameter passed in. This parameter value is not necessarily
-+  // equal to sizeof(MDTuple), it can be greater.
-+  std::size_t OSize = NumOps * sizeof(MDOperand);
-+  OSize = RoundUpToAlignment(OSize, llvm::alignOf<uint64_t>());
-+
-+  std::size_t RSize = Size + OSize + sizeof(Metadata) + sizeof(uintptr_t);
-+  RSize = RoundUpToAlignment(RSize, llvm::alignOf<uint64_t>());
-+  std::size_t Alignment = llvm::alignOf<uint64_t>();
-+
-+  void *P;
-+
-+#if defined(_MSC_VER)
-+  P = _aligned_malloc(RSize, Alignment);
-+  assert(P && "_aligned_malloc failed!");
-+  if (!P) return 0;
-+#else
-+  int R = posix_memalign(&P, Alignment, RSize);
-+  assert((R == 0) && "posix_memalign failed!");
-+  if (R != 0) return 0;
-+#endif
-+
-+  (void) std::memset(P, 0, RSize);
-+  unsigned char *UC = static_cast<unsigned char*>(P);
-+  MDNode *MN = reinterpret_cast<MDNode*>((UC + RSize) - Size);
-+
-+  MDOperand *O = reinterpret_cast<MDOperand*>(MN);
-+  MDOperand *MO;
-+
-+  for (MDOperand *E = O - NumOps; O != E; --O) {
-+    MO = new (O - 1) MDOperand();
-+    assert(MO && "MDOperand placement new failed!");
-+  }
-+
-+  // We store the address of the aligned allocated buffer
-+  // in the last extra element of the buffer. This address
-+  // will be used by the corresponding operator delete to
-+  // free the correct address.
-+  uintptr_t *U = reinterpret_cast<uintptr_t*>(O - 1);
-+  *U = reinterpret_cast<uintptr_t>(P);
-+  return MN;
-+}
-+
-+void MDNode::operator delete(void *Mem) throw() {
-+  MDNode *MN = reinterpret_cast<MDNode *>(Mem);
-+  Metadata *MTD = static_cast<Metadata*>(MN);
-+  std::size_t OSize = MN->NumOperands * sizeof(MDOperand);
-+  OSize = RoundUpToAlignment(OSize, llvm::alignOf<uint64_t>());
- 
--void MDNode::operator delete(void *Mem) {
--  MDNode *N = static_cast<MDNode *>(Mem);
-   MDOperand *O = static_cast<MDOperand *>(Mem);
--  for (MDOperand *E = O - N->NumOperands; O != E; --O)
--    (O - 1)->~MDOperand();
--  ::operator delete(O);
-+
-+  for (MDOperand *E = O - MN->NumOperands; O != E; --O) {
-+    MDOperand *MO = (O - 1);
-+    MO->~MDOperand();
- }
- 
--MDNode::MDNode(LLVMContext &Context, unsigned ID, ArrayRef<Metadata *> MDs)
--    : Metadata(ID), Context(Context), NumOperands(MDs.size()),
-+  MTD->~Metadata();
-+  MN->~MDNode();
-+
-+  // This is the address of the allocated buffer in the
-+  // extra buffer space allocated by operator new.
-+  uintptr_t *U = reinterpret_cast<uintptr_t*>(O - 1);
-+  std::free(reinterpret_cast<void*>(*U));
-+}
-+
-+MDNode::MDNode(LLVMContext &Ctx, unsigned ID, ArrayRef<Metadata *> MDs)
-+  : Metadata(ID), Context(Ctx), NumOperands(MDs.size()),
-       MDNodeSubclassData(0) {
-   for (unsigned I = 0, E = MDs.size(); I != E; ++I)
-     setOperand(I, MDs[I]);
-@@ -416,7 +476,7 @@
- 
- UniquableMDNode::UniquableMDNode(LLVMContext &C, unsigned ID,
-                                  ArrayRef<Metadata *> Vals, bool AllowRAUW)
--    : MDNode(C, ID, Vals) {
-+  : MDNode(C, ID, Vals), ReplaceableUses() {
-   if (!AllowRAUW)
-     return;
- 
-@@ -428,7 +488,7 @@
-   if (!NumUnresolved)
-     return;
- 
--  ReplaceableUses.reset(new ReplaceableMetadataImpl);
-+  ReplaceableUses.reset(new ReplaceableMetadataImpl());
-   SubclassData32 = NumUnresolved;
- }
- 
-@@ -577,6 +637,9 @@
-     llvm_unreachable("Invalid subclass of UniquableMDNode");
- #define HANDLE_UNIQUABLE_LEAF(CLASS)                                           \
-   case CLASS##Kind:                                                            \
-+    static_assert(llvm::AlignOf<uint64_t>::Alignment >=             \
-+        llvm::AlignOf<CLASS>::Alignment,                            \
-+        "Insufficient alignment for objects prepended to " #CLASS); \
-     delete cast<CLASS>(this);                                                  \
-     break;
- #include "llvm/IR/Metadata.def"
-@@ -589,6 +652,9 @@
-     llvm_unreachable("Invalid subclass of UniquableMDNode");
- #define HANDLE_UNIQUABLE_LEAF(CLASS)                                           \
-   case CLASS##Kind:                                                            \
-+    static_assert(llvm::AlignOf<uint64_t>::Alignment >=             \
-+        llvm::AlignOf<CLASS>::Alignment,                            \
-+        "Insufficient alignment for objects prepended to " #CLASS); \
-     return cast<CLASS>(this)->uniquifyImpl();
- #include "llvm/IR/Metadata.def"
-   }
-@@ -600,6 +666,9 @@
-     llvm_unreachable("Invalid subclass of UniquableMDNode");
- #define HANDLE_UNIQUABLE_LEAF(CLASS)                                           \
-   case CLASS##Kind:                                                            \
-+    static_assert(llvm::AlignOf<uint64_t>::Alignment >=             \
-+        llvm::AlignOf<CLASS>::Alignment,                            \
-+        "Insufficient alignment for objects prepended to " #CLASS); \
-     cast<CLASS>(this)->eraseFromStoreImpl();                                   \
-     break;
- #include "llvm/IR/Metadata.def"
-@@ -643,7 +712,91 @@
-   return *I;
- }
- 
--void MDTuple::eraseFromStoreImpl() { getContext().pImpl->MDTuples.erase(this); }
-+void MDTuple::eraseFromStoreImpl() {
-+  getContext().pImpl->MDTuples.erase(this);
-+}
-+
-+void *MDTuple::operator new(size_t Size, unsigned NumOps) throw() {
-+  assert((Size >= sizeof(MDTuple)) && "Insufficient size to operator new!");
-+
-+  std::size_t OSize = NumOps * sizeof(MDOperand);
-+  OSize = RoundUpToAlignment(OSize, llvm::alignOf<uint64_t>());
-+
-+  // Allocate extra space for an uintptr_t at the beginning of the
-+  // buffer.  This uintptr_t is where we will store the address of
-+  // the memory-aligned storage buffer. It will be plasced immediately
-+  // after the last MDOperand.
-+  // This address will be computed by the matching operator delete.
-+  // The total amount of space allocated must include the Size
-+  // parameter passed in. This parameter value is not necessarily
-+  // equal to sizeof(MDTuple), it can be greater.
-+  std::size_t RSize = Size + OSize + sizeof(UniquableMDNode) +
-+    sizeof(uintptr_t);
-+  RSize = RoundUpToAlignment(RSize, llvm::alignOf<uint64_t>());
-+  std::size_t Alignment = llvm::alignOf<uint64_t>();
-+
-+  void *P;
-+
-+#if defined(_MSC_VER)
-+  P = _aligned_malloc(RSize, Alignment);
-+  assert(P && "_aligned_malloc failed!");
-+  if (!P) return 0;
-+#else
-+  int R = posix_memalign(&P, Alignment, RSize);
-+  assert((R == 0) && "posix_memalign failed!");
-+  if (R != 0) return 0;
-+#endif
-+
-+  (void) std::memset(P, 0, RSize);
-+
-+  // Set a valid pointer to the address which will be returned
-+  // by this operator. This will be a pointer to a MDTuple.
-+  unsigned char *UC = static_cast<unsigned char*>(P);
-+  MDTuple *MDT = reinterpret_cast<MDTuple*>((UC + RSize) - Size);
-+  MDNode *MN = static_cast<MDNode*>(MDT);
-+
-+  MDOperand *O = reinterpret_cast<MDOperand*>(MN);
-+  MDOperand *MO;
-+
-+  for (MDOperand *E = O - NumOps; O != E; --O) {
-+    MO = new (O - 1) MDOperand();
-+    assert(MO && "MDOperand placement new failed!");
-+  }
-+
-+  // We store the address of the aligned allocated buffer
-+  // in the last extra element of the buffer. This address
-+  // will be used by the corresponding operator delete to
-+  // free the correct address.
-+  uintptr_t *U = reinterpret_cast<uintptr_t*>(O - 1);
-+  *U = reinterpret_cast<uintptr_t>(P);
-+  return MDT;
-+}
-+
-+void MDTuple::operator delete(void *Mem) throw() {
-+  MDTuple *MDT = reinterpret_cast<MDTuple*>(Mem);
-+  UniquableMDNode *UMN = static_cast<UniquableMDNode*>(MDT);
-+  MDNode *MN = static_cast<MDNode*>(UMN);
-+  unsigned NumOperands = MN->getNumOperands();
-+
-+  std::size_t OSize = NumOperands * sizeof(MDOperand);
-+  OSize = RoundUpToAlignment(OSize, llvm::alignOf<uint64_t>());
-+
-+  MDOperand *O =
-+    reinterpret_cast<MDOperand*>(reinterpret_cast<void*>(MN));
-+  for (MDOperand *E = O - NumOperands; O != E; --O) {
-+    MDOperand *MO = (O - 1);
-+    MO->~MDOperand();
-+  }
-+
-+  // This is teh address of the allocated buffer in the
-+  // extra space allocated by operator new in RSize.
-+  uintptr_t *U = reinterpret_cast<uintptr_t*>(O - 1);
-+
-+  UMN->~UniquableMDNode();
-+  MDT->~MDTuple();
-+  std::free(reinterpret_cast<void*>(*U));
-+}
-+
- 
- MDLocation::MDLocation(LLVMContext &C, unsigned Line, unsigned Column,
-                        ArrayRef<Metadata *> MDs, bool AllowRAUW)
-@@ -675,6 +828,88 @@
-     Line = 0;
- }
- 
-+void *MDLocation::operator new(size_t Size, unsigned NumOps) throw() {
-+  assert((Size >= sizeof(MDLocation)) && "Insufficient size to operator new!");
-+
-+  std::size_t OSize = NumOps * sizeof(MDOperand);
-+  OSize = RoundUpToAlignment(OSize, llvm::alignOf<uint64_t>());
-+
-+  // Allocate extra space for an uintptr_t at the beginning of the
-+  // buffer.  This uintptr_t is where we will store the address of
-+  // the memory-aligned storage buffer. It will be plasced immediately
-+  // after the last MDOperand.
-+  // This address will be computed by the matching operator delete.
-+  // The total amount of space allocated must include the Size
-+  // parameter passed in. This parameter value is not necessarily
-+  // equal to sizeof(MDLocation), it can be greater.
-+  std::size_t RSize =
-+    Size + OSize + sizeof(UniquableMDNode) + sizeof(uintptr_t);
-+  RSize = RoundUpToAlignment(RSize, llvm::alignOf<uint64_t>());
-+  std::size_t Alignment = llvm::alignOf<uint64_t>();
-+
-+  void *P;
-+
-+#if defined(_MSC_VER)
-+  P = _aligned_malloc(RSize, Alignment);
-+  assert(P && "_aligned_malloc failed!");
-+  if (!P) return 0;
-+#else
-+  int R = posix_memalign(&P, Alignment, RSize);
-+  assert((R == 0) && "posix_memalign failed!");
-+  if (R != 0) return 0;
-+#endif
-+
-+  (void) std::memset(P, 0, RSize);
-+
-+
-+  // Set a valid pointer to the address which will be returned
-+  // by this operator. This will be a pointer to a MDLocation.
-+  unsigned char *UC = static_cast<unsigned char*>(P);
-+  MDLocation *MDL = reinterpret_cast<MDLocation*>((UC + RSize) - Size);
-+  MDNode *MN = static_cast<MDNode*>(MDL);
-+
-+  MDOperand *O = reinterpret_cast<MDOperand*>(MN);
-+  MDOperand *MO;
-+
-+  for (MDOperand *E = O - NumOps; O != E; --O) {
-+    MO = new (O - 1) MDOperand();
-+    assert(MO && "MDOperand placement new failed!");
-+  }
-+
-+  // We store the address of the aligned allocated buffer
-+  // in the last extra element of the buffer. This address
-+  // will be used by the corresponding operator delete to
-+  // free the correct address.
-+  uintptr_t *U = reinterpret_cast<uintptr_t*>(O - 1);
-+  *U = reinterpret_cast<uintptr_t>(P);
-+  return MDL;
-+}
-+
-+void MDLocation::operator delete(void *Mem) throw() {
-+  MDLocation *MDL = reinterpret_cast<MDLocation*>(Mem);
-+  UniquableMDNode *UMN = static_cast<UniquableMDNode*>(MDL);
-+  MDNode *MN = static_cast<MDNode*>(UMN);
-+  unsigned NumOperands = MN->getNumOperands();
-+
-+  std::size_t OSize = NumOperands * sizeof(MDOperand);
-+  OSize = RoundUpToAlignment(OSize, llvm::alignOf<uint64_t>());
-+
-+  MDOperand *O =
-+    reinterpret_cast<MDOperand*>(reinterpret_cast<void*>(MN));
-+  for (MDOperand *E = O - NumOperands; O != E; --O) {
-+    MDOperand *MO = (O - 1);
-+    MO->~MDOperand();
-+  }
-+
-+  // This is the address of the allocated buffer in the
-+  // extra space allocated by operator new in RSize.
-+  uintptr_t *U = reinterpret_cast<uintptr_t*>(O - 1);
-+
-+  MDL->~MDLocation();
-+  UMN->~UniquableMDNode();
-+  std::free(reinterpret_cast<void*>(*U));
-+}
-+
- static void adjustColumn(unsigned &Column) {
-   // Set to unknown on overflow.  Still use 8 bits for now.
-   if (Column >= (1u << 8))
-@@ -969,6 +1204,96 @@
- }
- 
- //===----------------------------------------------------------------------===//
-+// MDNodeFwdDecl implementation.
-+//
-+
-+void *MDNodeFwdDecl::operator new(size_t Size, unsigned NumOps) throw() {
-+  assert((Size >= sizeof(MDNodeFwdDecl)) && "Insufficient space to operator new!");
-+
-+  std::size_t OSize = NumOps * sizeof(MDOperand);
-+  OSize = RoundUpToAlignment(OSize, llvm::alignOf<uint64_t>());
-+
-+  // Allocate extra space for an uintptr_t at the beginning of the
-+  // buffer.  This uintptr_t is where we will store the address of
-+  // the memory-aligned storage buffer. It will be plasced immediately
-+  // after the last MDOperand.
-+  // This address will be computed by the matching operator delete.
-+  // The total amount of space allocated must include the Size
-+  // parameter passed in. This parameter value is not necessarily
-+  // equal to sizeof(MDTuple), it can be greater.
-+  std::size_t RSize =
-+    Size +  OSize + sizeof(MDNode) + sizeof(ReplaceableMetadataImpl) +
-+    sizeof(uintptr_t);
-+  RSize = RoundUpToAlignment(RSize, llvm::alignOf<uint64_t>());
-+  std::size_t Alignment = llvm::alignOf<uint64_t>();
-+
-+  void *P;
-+
-+#if defined(_MSC_VER)
-+  P = _aligned_malloc(RSize, Alignment);
-+  assert(P && "_aligned_malloc failed!");
-+  if (!P) return 0;
-+#else
-+  int R = posix_memalign(&P, Alignment, RSize);
-+  assert((R == 0) && "posix_memalign failed!");
-+  if (R != 0) return 0;
-+#endif
-+
-+  (void) std::memset(P, 0, RSize);
-+
-+  // Set a valid pointer to the address which will be returned
-+  // by this operator. This will be a pointer to a MDNodeFwdDecl.
-+  unsigned char *UC = static_cast<unsigned char*>(P);
-+  MDNodeFwdDecl *MFD =
-+    reinterpret_cast<MDNodeFwdDecl*>((UC + RSize) -
-+        (Size + sizeof(ReplaceableMetadataImpl)));
-+  MDNode *MN = static_cast<MDNode*>(MFD);
-+  ReplaceableMetadataImpl *RMI = static_cast<ReplaceableMetadataImpl*>(MFD);
-+
-+  MDOperand *O = reinterpret_cast<MDOperand*>(MN);
-+  MDOperand *MO;
-+
-+  for (MDOperand *E = O - NumOps; O != E; --O) {
-+    MO = new (O - 1) MDOperand();
-+    assert(MO && "MDOperand placement new failed!");
-+  }
-+
-+  // We store the address of the aligned allocated buffer
-+  // in the last extra element of the buffer. This address
-+  // will be used by the corresponding operator delete to
-+  // free the correct address.
-+  uintptr_t *U = reinterpret_cast<uintptr_t*>(O - 1);
-+  *U = reinterpret_cast<uintptr_t>(P);
-+  return MFD;
-+}
-+
-+void MDNodeFwdDecl::operator delete(void *Mem) throw() {
-+  MDNodeFwdDecl *MFD = reinterpret_cast<MDNodeFwdDecl*>(Mem);
-+  ReplaceableMetadataImpl *RMI =
-+    static_cast<ReplaceableMetadataImpl*>(MFD);
-+  MDNode *MN = static_cast<MDNode*>(MFD);
-+
-+  std::size_t OSize = MN->getNumOperands() * sizeof(MDOperand);
-+  OSize = RoundUpToAlignment(OSize, llvm::alignOf<uint64_t>());
-+
-+  MDOperand *O =
-+    reinterpret_cast<MDOperand*>(reinterpret_cast<void*>(MN));
-+  for (MDOperand *E = O - MN->getNumOperands(); O != E; --O) {
-+    MDOperand *MO = (O - 1);
-+    MO->~MDOperand();
-+  }
-+
-+  // This is the address of the allocated buffer in the
-+  // extra space allocated by operator new in RSize.
-+  uintptr_t *U = reinterpret_cast<uintptr_t*>(O - 1);
-+
-+  // Do not perform a full canonical destructor sequence here because
-+  // MDNodeFwdDecl's are being deleted by ReplaceableMetadataImpl's
-+  // destructor, which gets called from MDNode::deleteTemporary().
-+  std::free(reinterpret_cast<void*>(*U));
-+}
-+
-+//===----------------------------------------------------------------------===//
- // NamedMDNode implementation.
- //
- 
---- lib/Support/SmallVector.cpp	2012-08-21 17:11:07.000000000 -0700
-+++ lib/Support/SmallVector.cpp	2015-08-26 21:28:23.352666372 -0700
-@@ -11,9 +11,13 @@
- //
- //===----------------------------------------------------------------------===//
- 
-+#include "llvm/Support/MathExtras.h"
-+#include "llvm/Support/raw_ostream.h"
- #include "llvm/ADT/SmallVector.h"
- using namespace llvm;
- 
-+#include <stdlib.h>
-+
- /// grow_pod - This is an implementation of the grow() method which only works
- /// on POD-like datatypes and is out of line to reduce code duplication.
- void SmallVectorBase::grow_pod(void *FirstEl, size_t MinSizeInBytes,
-@@ -23,15 +27,42 @@
-   if (NewCapacityInBytes < MinSizeInBytes)
-     NewCapacityInBytes = MinSizeInBytes;
- 
-+  NewCapacityInBytes =
-+    llvm::RoundUpToAlignment(NewCapacityInBytes, llvm::alignOf<uint64_t>());
-+
-   void *NewElts;
-   if (BeginX == FirstEl) {
--    NewElts = malloc(NewCapacityInBytes);
-+    unsigned Alignment = llvm::alignOf<uint64_t>();
-+#if defined(_MSC_VER)
-+    NewElts = _aligned_malloc(Alignment, NewCapacityInBytes);
-+    assert(NewElts && "_aligned_malloc failed!");
-+#else
-+    int R = posix_memalign(&NewElts, Alignment, NewCapacityInBytes);
-+    assert((R == 0) && "posix_memalign failed!");
-+#endif
-+
-+    assert(NewElts && "Invalid pointer after aligned allocation!");
-+    (void) std::memset(NewElts, 0, NewCapacityInBytes);
- 
-     // Copy the elements over.  No need to run dtors on PODs.
--    memcpy(NewElts, this->BeginX, CurSizeBytes);
-+    (void) std::memcpy(NewElts, this->BeginX, CurSizeBytes);
-   } else {
-     // If this wasn't grown from the inline copy, grow the allocated space.
--    NewElts = realloc(this->BeginX, NewCapacityInBytes);
-+    unsigned Alignment = llvm::alignOf<uint64_t>();
-+#if defined(_MSC_VER)
-+    NewElts = _aligned_malloc(Alignment, NewCapacityInBytes);
-+    assert(NewElts && "_aligned_malloc failed!");
-+#else
-+    int R = posix_memalign(&NewElts, Alignment, NewCapacityInBytes);
-+    assert((R == 0) && "posix_memalign failed!");
-+#endif
-+
-+    assert(NewElts && "Invalid pointer after aligned allocation!");
-+    (void) std::memset(NewElts, 0, NewCapacityInBytes);
-+
-+    // Copy the elements over.  No need to run dtors on PODs.
-+    (void) std::memcpy(NewElts, this->BeginX, CurSizeBytes);
-+    std::free(this->BeginX);
-   }
- 
-   this->EndX = (char*)NewElts+CurSizeBytes;
---- tools/clang/lib/AST/NestedNameSpecifier.cpp	2014-09-25 17:28:20.000000000 -0700
-+++ tools/clang/lib/AST/NestedNameSpecifier.cpp	2015-08-26 08:27:36.324291508 -0700
-@@ -437,20 +437,37 @@
-               unsigned &BufferCapacity) {
-     if (BufferSize + (End - Start) > BufferCapacity) {
-       // Reallocate the buffer.
--      unsigned NewCapacity 
--      = std::max((unsigned)(BufferCapacity? BufferCapacity * 2 
--                            : sizeof(void*) * 2),
--                 (unsigned)(BufferSize + (End - Start)));
--      char *NewBuffer = static_cast<char *>(malloc(NewCapacity));
--      memcpy(NewBuffer, Buffer, BufferSize);
-+      unsigned NewCapacity =
-+        std::max((unsigned)(BufferCapacity? BufferCapacity * 2 
-+              : sizeof(void*) * 2), (unsigned)(BufferSize + (End - Start)));
-+      NewCapacity =
-+        llvm::RoundUpToAlignment(NewCapacity, llvm::alignOf<uint64_t>());
-+      unsigned Alignment = ((NewCapacity < 5) ? 4 : 8);
-+      if (NewCapacity < Alignment)
-+        NewCapacity = Alignment;
-       
--      if (BufferCapacity)
-+      char *NewBuffer;
-+#if defined(_MSC_VER)
-+      NewBuffer = _aligned_malloc((size_t) NewCapacity, (size_t) Alignment);
-+      assert(NewBuffer && "_aligned_malloc failed!");
-+#else
-+      int R = posix_memalign((void**) &NewBuffer, Alignment, NewCapacity);
-+
-+      assert((R == 0) && "posix_memalign failed!");
-+      assert(NewBuffer && "Memory allocation failed!");
-+#endif
-+
-+      if ((Buffer != 0) && (BufferSize > 0))
-+        (void) std::memcpy(NewBuffer, Buffer, BufferSize);
-+
-+      if ((Buffer != 0) && (BufferSize > 0))
-         free(Buffer);
-+
-       Buffer = NewBuffer;
-       BufferCapacity = NewCapacity;
-     }
-     
--    memcpy(Buffer + BufferSize, Start, End - Start);
-+    (void) std::memcpy(Buffer + BufferSize, Start, End - Start);
-     BufferSize += End-Start;
-   }
-   
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/015-solaris-clang-tools-driver.patch	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,131 @@
+# 24314638 LLVM CommandLine subsystem is busted
+# Various cleanup fixes.
+# 3.9.X upstream.
+--- tools/clang/tools/driver/driver.cpp	2016-01-25 12:35:13.000000000 -0800
++++ tools/clang/tools/driver/driver.cpp	2016-05-11 18:39:13.438899360 -0700
+@@ -48,6 +48,8 @@
+ #include "llvm/Support/TargetSelect.h"
+ #include "llvm/Support/Timer.h"
+ #include "llvm/Support/raw_ostream.h"
++
++#include <vector>
+ #include <memory>
+ #include <system_error>
+ using namespace clang;
+@@ -97,7 +99,7 @@
+ /// \param Edit - The override command to perform.
+ /// \param SavedStrings - Set to use for storing string representations.
+ static void ApplyOneQAOverride(raw_ostream &OS,
+-                               SmallVectorImpl<const char*> &Args,
++                               std::vector<const char*> &Args,
+                                StringRef Edit,
+                                std::set<std::string> &SavedStrings) {
+   // This does not need to be efficient.
+@@ -169,7 +171,7 @@
+ 
+ /// ApplyQAOverride - Apply a comma separate list of edits to the
+ /// input argument lists. See ApplyOneQAOverride.
+-static void ApplyQAOverride(SmallVectorImpl<const char*> &Args,
++static void ApplyQAOverride(std::vector<const char*> &Args,
+                             const char *OverrideStr,
+                             std::set<std::string> &SavedStrings) {
+   raw_ostream *OS = &llvm::errs();
+@@ -202,7 +204,7 @@
+                       void *MainAddr);
+ 
+ static void insertTargetAndModeArgs(StringRef Target, StringRef Mode,
+-                                    SmallVectorImpl<const char *> &ArgVector,
++                                    std::vector<const char *> &ArgVector,
+                                     std::set<std::string> &SavedStrings) {
+   if (!Mode.empty()) {
+     // Add the mode flag to the arguments.
+@@ -222,7 +224,7 @@
+ }
+ 
+ static void getCLEnvVarOptions(std::string &EnvValue, llvm::StringSaver &Saver,
+-                               SmallVectorImpl<const char *> &Opts) {
++                               std::vector<const char *> &Opts) {
+   llvm::cl::TokenizeWindowsCommandLine(EnvValue, Saver, Opts);
+   // The first instance of '#' should be replaced with '=' in each option.
+   for (const char *Opt : Opts)
+@@ -260,12 +262,15 @@
+ // This lets us create the DiagnosticsEngine with a properly-filled-out
+ // DiagnosticOptions instance.
+ static DiagnosticOptions *
+-CreateAndPopulateDiagOpts(ArrayRef<const char *> argv) {
+-  auto *DiagOpts = new DiagnosticOptions;
++CreateAndPopulateDiagOpts(std::vector<const char *> &Argv) {
++  auto *DiagOpts = new DiagnosticOptions();
+   std::unique_ptr<OptTable> Opts(createDriverOptTable());
+-  unsigned MissingArgIndex, MissingArgCount;
++  unsigned MissingArgIndex = 0U;
++  unsigned MissingArgCount = 0U;
++  llvm::ArrayRef<const char*> AAR(Argv.data(), Argv.size());
+   InputArgList Args =
+-      Opts->ParseArgs(argv.slice(1), MissingArgIndex, MissingArgCount);
++    Opts->ParseArgs(AAR.slice(1), MissingArgIndex, MissingArgCount);
++
+   // We ignore MissingArgCount and the return value of ParseDiagnosticArgs.
+   // Any errors that would be diagnosed here will also be diagnosed later,
+   // when the DiagnosticsEngine actually exists.
+@@ -273,12 +278,12 @@
+   return DiagOpts;
+ }
+ 
+-static void SetInstallDir(SmallVectorImpl<const char *> &argv,
++static void SetInstallDir(std::vector<const char *> &argv,
+                           Driver &TheDriver, bool CanonicalPrefixes) {
+   // Attempt to find the original path used to invoke the driver, to determine
+   // the installed path. We do this manually, because we want to support that
+   // path being a symlink.
+-  SmallString<128> InstalledPath(argv[0]);
++  SmallString<PATH_MAX> InstalledPath(argv[0]);
+ 
+   // Do a PATH lookup, if there are no directory components.
+   if (llvm::sys::path::filename(InstalledPath) == InstalledPath)
+@@ -314,10 +319,9 @@
+   if (llvm::sys::Process::FixupStandardFileDescriptors())
+     return 1;
+ 
+-  SmallVector<const char *, 256> argv;
+-  llvm::SpecificBumpPtrAllocator<char> ArgAllocator;
+-  std::error_code EC = llvm::sys::Process::GetArgumentVector(
+-      argv, llvm::makeArrayRef(argv_, argc_), ArgAllocator);
++  std::vector<const char *> argv;
++  llvm::ArrayRef<const char*> AAR = llvm::makeArrayRef(argv_, argc_);
++  std::error_code EC = llvm::sys::Process::GetArgumentVector(argv, AAR);
+   if (EC) {
+     llvm::errs() << "error: couldn't get arguments: " << EC.message() << '\n';
+     return 1;
+@@ -383,7 +387,7 @@
+     // Arguments in "CL" are prepended.
+     llvm::Optional<std::string> OptCL = llvm::sys::Process::GetEnv("CL");
+     if (OptCL.hasValue()) {
+-      SmallVector<const char *, 8> PrependedOpts;
++      std::vector<const char*> PrependedOpts;
+       getCLEnvVarOptions(OptCL.getValue(), Saver, PrependedOpts);
+ 
+       // Insert right after the program name to prepend to the argument list.
+@@ -392,11 +396,11 @@
+     // Arguments in "_CL_" are appended.
+     llvm::Optional<std::string> Opt_CL_ = llvm::sys::Process::GetEnv("_CL_");
+     if (Opt_CL_.hasValue()) {
+-      SmallVector<const char *, 8> AppendedOpts;
++      std::vector<const char*> AppendedOpts;
+       getCLEnvVarOptions(Opt_CL_.getValue(), Saver, AppendedOpts);
+ 
+       // Insert at the end of the argument list to append.
+-      argv.append(AppendedOpts.begin(), AppendedOpts.end());
++      argv.insert(argv.end(), AppendedOpts.begin(), AppendedOpts.end());
+     }
+   }
+ 
+@@ -441,7 +445,7 @@
+ 
+   std::unique_ptr<Compilation> C(TheDriver.BuildCompilation(argv));
+   int Res = 0;
+-  SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
++  SmallVector<std::pair<int, const Command *>, 8> FailingCommands;
+   if (C.get())
+     Res = TheDriver.ExecuteCompilation(*C, FailingCommands);
+ 
--- a/components/llvm/patches/016-llvm-21851513-memory-corruption.patch	Thu Jul 28 16:15:45 2016 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,3107 +0,0 @@
-# 21851513 severe memory corruption in the LLVM command-line parsing module
-# 21870103 TableGen makes incorrect assumptions about anonymous namespace instantiation
-# 21870087 naming convention for the InputFile key is inconsistent across LLVM utilities
-# 21870099 128 bytes for a filesystem path is definitely not enough
-# clang makes incorrect assumptions about anonymous namespace instantiation order
-# For upstream - maybe.
---- include/llvm/Support/ThreadLocal.h	2014-12-14 17:04:45.000000000 -0800
-+++ include/llvm/Support/ThreadLocal.h	2015-09-16 14:08:58.000000000 -0700
-@@ -21,24 +21,22 @@
- namespace llvm {
-   namespace sys {
-     // ThreadLocalImpl - Common base class of all ThreadLocal instantiations.
-     // YOU SHOULD NEVER USE THIS DIRECTLY.
-     class ThreadLocalImpl {
-       typedef uint64_t ThreadLocalDataTy;
-       /// \brief Platform-specific thread local data.
-       ///
-       /// This is embedded in the class and we avoid malloc'ing/free'ing it,
-       /// to make this class more safe for use along with CrashRecoveryContext.
--      union {
--        char data[sizeof(ThreadLocalDataTy)];
--        ThreadLocalDataTy align_data;
--      };
-+      uint64_t data[2];
-+
-     public:
-       ThreadLocalImpl();
-       virtual ~ThreadLocalImpl();
-       void setInstance(const void* d);
-       void *getInstance();
-       void removeInstance();
-     };
- 
-     /// ThreadLocal - A class used to abstract thread-local storage.  It holds,
-     /// for each thread, a pointer a single object of type T.
---- lib/Support/MemoryBuffer.cpp	2014-12-12 14:27:53.000000000 -0800
-+++ lib/Support/MemoryBuffer.cpp	2015-09-19 14:20:06.472430028 -0700
-@@ -21,25 +21,29 @@
- #include "llvm/Support/Path.h"
- #include "llvm/Support/Process.h"
- #include "llvm/Support/Program.h"
- #include <cassert>
- #include <cerrno>
- #include <cstdio>
- #include <cstring>
- #include <new>
- #include <sys/types.h>
- #include <system_error>
-+
- #if !defined(_MSC_VER) && !defined(__MINGW32__)
- #include <unistd.h>
- #else
- #include <io.h>
- #endif
-+
-+#include <climits>
-+
- using namespace llvm;
- 
- //===----------------------------------------------------------------------===//
- // MemoryBuffer implementation itself.
- //===----------------------------------------------------------------------===//
- 
- MemoryBuffer::~MemoryBuffer() { }
- 
- /// init - Initialize this MemoryBuffer as a reference to externally allocated
- /// memory, memory that we know is already null terminated.
-@@ -63,21 +67,21 @@
- }
- 
- namespace {
- struct NamedBufferAlloc {
-   const Twine &Name;
-   NamedBufferAlloc(const Twine &Name) : Name(Name) {}
- };
- }
- 
- void *operator new(size_t N, const NamedBufferAlloc &Alloc) {
--  SmallString<256> NameBuf;
-+  SmallString<PATH_MAX> NameBuf;
-   StringRef NameRef = Alloc.Name.toStringRef(NameBuf);
- 
-   char *Mem = static_cast<char *>(operator new(N + NameRef.size() + 1));
-   CopyStringRef(Mem + N, NameRef);
-   return Mem;
- }
- 
- namespace {
- /// MemoryBufferMem - Named MemoryBuffer pointing to a block of memory.
- class MemoryBufferMem : public MemoryBuffer {
-@@ -156,21 +160,21 @@
- MemoryBuffer::getNewMemBuffer(size_t Size, StringRef BufferName) {
-   std::unique_ptr<MemoryBuffer> SB = getNewUninitMemBuffer(Size, BufferName);
-   if (!SB)
-     return nullptr;
-   memset(const_cast<char*>(SB->getBufferStart()), 0, Size);
-   return SB;
- }
- 
- ErrorOr<std::unique_ptr<MemoryBuffer>>
- MemoryBuffer::getFileOrSTDIN(const Twine &Filename, int64_t FileSize) {
--  SmallString<256> NameBuf;
-+  SmallString<PATH_MAX> NameBuf;
-   StringRef NameRef = Filename.toStringRef(NameBuf);
- 
-   if (NameRef == "-")
-     return getSTDIN();
-   return getFile(Filename, FileSize);
- }
- 
- ErrorOr<std::unique_ptr<MemoryBuffer>>
- MemoryBuffer::getFileSlice(const Twine &FilePath, uint64_t MapSize, 
-                            uint64_t Offset) {
---- lib/Support/Unix/Program.inc	2014-12-01 16:52:01.000000000 -0800
-+++ lib/Support/Unix/Program.inc	2015-09-19 15:34:57.144042911 -0700
-@@ -31,23 +31,20 @@
- #if HAVE_SIGNAL_H
- #include <signal.h>
- #endif
- #if HAVE_FCNTL_H
- #include <fcntl.h>
- #endif
- #if HAVE_UNISTD_H
- #include <unistd.h>
- #endif
- #ifdef HAVE_POSIX_SPAWN
--#ifdef __sun__
--#define  _RESTRICT_KYWD
--#endif
- #include <spawn.h>
- #if !defined(__APPLE__)
-   extern char **environ;
- #else
- #include <crt_externs.h> // _NSGetEnviron
- #endif
- #endif
- 
- namespace llvm {
- 
---- lib/TableGen/Main.cpp	2014-12-10 23:04:54.000000000 -0800
-+++ lib/TableGen/Main.cpp	2015-09-19 18:04:08.147911223 -0700
-@@ -21,97 +21,118 @@
- #include "llvm/Support/MemoryBuffer.h"
- #include "llvm/Support/ToolOutputFile.h"
- #include "llvm/TableGen/Error.h"
- #include "llvm/TableGen/Main.h"
- #include "llvm/TableGen/Record.h"
- #include <algorithm>
- #include <cstdio>
- #include <system_error>
- using namespace llvm;
- 
--namespace {
--  cl::opt<std::string>
--  OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"),
--                 cl::init("-"));
--
--  cl::opt<std::string>
--  DependFilename("d",
--                 cl::desc("Dependency filename"),
--                 cl::value_desc("filename"),
--                 cl::init(""));
--
--  cl::opt<std::string>
--  InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
--
--  cl::list<std::string>
--  IncludeDirs("I", cl::desc("Directory of include files"),
--              cl::value_desc("directory"), cl::Prefix);
--}
-+static cl::opt<std::string>
-+OutputFilename(cl::Prefix, "o",
-+               cl::desc("Output filename"),
-+               cl::value_desc("filename"),
-+               cl::NotHidden,
-+               cl::Optional,
-+               cl::init("-"),
-+               cl::ValueRequired);
-+
-+static cl::opt<std::string>
-+DependFilename(cl::Prefix, "d",
-+               cl::desc("Dependency filename"),
-+               cl::value_desc("filename"),
-+               cl::NotHidden,
-+               cl::Optional,
-+               cl::init(""),
-+               cl::ValueRequired);
-+
-+static cl::opt<std::string>
-+InputFilename(cl::Positional, "<input file>",
-+              cl::desc("<input file>"),
-+              cl::value_desc("Input filename"),
-+              cl::NotHidden,
-+              cl::Optional,
-+              cl::init("-"),
-+              cl::ValuePositionalNoArgs);
-+
-+static cl::list<std::string>
-+IncludeDirs(cl::Prefix, "I",
-+            cl::desc("Directory of include files"),
-+            cl::value_desc("directory"),
-+            cl::NotHidden,
-+            cl::ZeroOrMore,
-+            cl::ValueRequired);
- 
- /// \brief Create a dependency file for `-d` option.
- ///
- /// This functionality is really only for the benefit of the build system.
- /// It is similar to GCC's `-M*` family of options.
- static int createDependencyFile(const TGParser &Parser, const char *argv0) {
-   if (OutputFilename == "-") {
-     errs() << argv0 << ": the option -d must be used together with -o\n";
-     return 1;
-   }
-   std::error_code EC;
-   tool_output_file DepOut(DependFilename, EC, sys::fs::F_Text);
-   if (EC) {
-     errs() << argv0 << ": error opening " << DependFilename << ":"
-            << EC.message() << "\n";
-     return 1;
-   }
-+
-   DepOut.os() << OutputFilename << ":";
-+
-   for (const auto &Dep : Parser.getDependencies()) {
-     DepOut.os() << ' ' << Dep.first;
-   }
-   DepOut.os() << "\n";
-   DepOut.keep();
-   return 0;
- }
- 
- namespace llvm {
- 
- int TableGenMain(char *argv0, TableGenMainFn *MainFn) {
-   RecordKeeper Records;
- 
-   // Parse the input file.
-+  llvm::Twine TFN(InputFilename);
-   ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
--      MemoryBuffer::getFileOrSTDIN(InputFilename);
-+      MemoryBuffer::getFileOrSTDIN(TFN);
-+
-   if (std::error_code EC = FileOrErr.getError()) {
-     errs() << "Could not open input file '" << InputFilename
--           << "': " << EC.message() << "\n";
-+      << "': " << EC.message() << "\n";
-     return 1;
-   }
- 
-   // Tell SrcMgr about this buffer, which is what TGParser will pick up.
-   SrcMgr.AddNewSourceBuffer(std::move(*FileOrErr), SMLoc());
- 
-   // Record the location of the include directory so that the lexer can find
-   // it later.
--  SrcMgr.setIncludeDirs(IncludeDirs);
-+  SrcMgr.setIncludeDirs(IncludeDirs.getStorage());
- 
-   TGParser Parser(SrcMgr, Records);
- 
-   if (Parser.ParseFile())
-     return 1;
- 
-   std::error_code EC;
-   tool_output_file Out(OutputFilename, EC, sys::fs::F_Text);
-   if (EC) {
-     errs() << argv0 << ": error opening " << OutputFilename << ":"
-            << EC.message() << "\n";
-     return 1;
-   }
-+
-   if (!DependFilename.empty()) {
-     if (int Ret = createDependencyFile(Parser, argv0))
-       return Ret;
-   }
- 
-   if (MainFn(Out.os(), Records))
-     return 1;
- 
-   if (ErrorsPrinted > 0) {
-     errs() << argv0 << ": " << ErrorsPrinted << " errors.\n";
---- utils/TableGen/TableGen.cpp	2014-12-10 23:04:54.000000000 -0800
-+++ utils/TableGen/TableGen.cpp	2015-09-14 16:23:45.000000000 -0700
-@@ -37,67 +37,67 @@
-   GenFastISel,
-   GenSubtarget,
-   GenIntrinsic,
-   GenTgtIntrinsic,
-   PrintEnums,
-   PrintSets,
-   GenOptParserDefs,
-   GenCTags
- };
- 
--namespace {
--  cl::opt<ActionType>
--  Action(cl::desc("Action to perform:"),
--         cl::values(clEnumValN(PrintRecords, "print-records",
--                               "Print all records to stdout (default)"),
--                    clEnumValN(GenEmitter, "gen-emitter",
--                               "Generate machine code emitter"),
--                    clEnumValN(GenRegisterInfo, "gen-register-info",
--                               "Generate registers and register classes info"),
--                    clEnumValN(GenInstrInfo, "gen-instr-info",
--                               "Generate instruction descriptions"),
--                    clEnumValN(GenCallingConv, "gen-callingconv",
--                               "Generate calling convention descriptions"),
--                    clEnumValN(GenAsmWriter, "gen-asm-writer",
--                               "Generate assembly writer"),
--                    clEnumValN(GenDisassembler, "gen-disassembler",
--                               "Generate disassembler"),
--                    clEnumValN(GenPseudoLowering, "gen-pseudo-lowering",
--                               "Generate pseudo instruction lowering"),
--                    clEnumValN(GenAsmMatcher, "gen-asm-matcher",
--                               "Generate assembly instruction matcher"),
--                    clEnumValN(GenDAGISel, "gen-dag-isel",
--                               "Generate a DAG instruction selector"),
--                    clEnumValN(GenDFAPacketizer, "gen-dfa-packetizer",
--                               "Generate DFA Packetizer for VLIW targets"),
--                    clEnumValN(GenFastISel, "gen-fast-isel",
--                               "Generate a \"fast\" instruction selector"),
--                    clEnumValN(GenSubtarget, "gen-subtarget",
--                               "Generate subtarget enumerations"),
--                    clEnumValN(GenIntrinsic, "gen-intrinsic",
--                               "Generate intrinsic information"),
--                    clEnumValN(GenTgtIntrinsic, "gen-tgt-intrinsic",
--                               "Generate target intrinsic information"),
--                    clEnumValN(PrintEnums, "print-enums",
--                               "Print enum values for a class"),
--                    clEnumValN(PrintSets, "print-sets",
--                               "Print expanded sets for testing DAG exprs"),
--                    clEnumValN(GenOptParserDefs, "gen-opt-parser-defs",
--                               "Generate option definitions"),
--                    clEnumValN(GenCTags, "gen-ctags",
--                               "Generate ctags-compatible index"),
--                    clEnumValEnd));
-+static cl::opt<ActionType>
-+Action(cl::desc("Action to perform:"),
-+       cl::values(clEnumValN(PrintRecords, "print-records",
-+                             "Print all records to stdout (default)"),
-+                  clEnumValN(GenEmitter, "gen-emitter",
-+                             "Generate machine code emitter"),
-+                  clEnumValN(GenRegisterInfo, "gen-register-info",
-+                             "Generate registers and register classes info"),
-+                  clEnumValN(GenInstrInfo, "gen-instr-info",
-+                             "Generate instruction descriptions"),
-+                  clEnumValN(GenCallingConv, "gen-callingconv",
-+                             "Generate calling convention descriptions"),
-+                  clEnumValN(GenAsmWriter, "gen-asm-writer",
-+                             "Generate assembly writer"),
-+                  clEnumValN(GenDisassembler, "gen-disassembler",
-+                             "Generate disassembler"),
-+                  clEnumValN(GenPseudoLowering, "gen-pseudo-lowering",
-+                             "Generate pseudo instruction lowering"),
-+                  clEnumValN(GenAsmMatcher, "gen-asm-matcher",
-+                             "Generate assembly instruction matcher"),
-+                  clEnumValN(GenDAGISel, "gen-dag-isel",
-+                             "Generate a DAG instruction selector"),
-+                  clEnumValN(GenDFAPacketizer, "gen-dfa-packetizer",
-+                             "Generate DFA Packetizer for VLIW targets"),
-+                  clEnumValN(GenFastISel, "gen-fast-isel",
-+                             "Generate a \"fast\" instruction selector"),
-+                  clEnumValN(GenSubtarget, "gen-subtarget",
-+                             "Generate subtarget enumerations"),
-+                  clEnumValN(GenIntrinsic, "gen-intrinsic",
-+                             "Generate intrinsic information"),
-+                  clEnumValN(GenTgtIntrinsic, "gen-tgt-intrinsic",
-+                             "Generate target intrinsic information"),
-+                  clEnumValN(PrintEnums, "print-enums",
-+                             "Print enum values for a class"),
-+                  clEnumValN(PrintSets, "print-sets",
-+                             "Print expanded sets for testing DAG exprs"),
-+                  clEnumValN(GenOptParserDefs, "gen-opt-parser-defs",
-+                             "Generate option definitions"),
-+                  clEnumValN(GenCTags, "gen-ctags",
-+                             "Generate ctags-compatible index"),
-+                  clEnumValEnd));
- 
--  cl::opt<std::string>
--  Class("class", cl::desc("Print Enum list for this class"),
--          cl::value_desc("class name"));
-+static cl::opt<std::string>
-+Class("class", cl::desc("Print Enum list for this class"),
-+      cl::value_desc("class name"));
- 
-+namespace {
- bool LLVMTableGenMain(raw_ostream &OS, RecordKeeper &Records) {
-   switch (Action) {
-   case PrintRecords:
-     OS << Records;           // No argument, dump all contents
-     break;
-   case GenEmitter:
-     EmitCodeEmitter(Records, OS);
-     break;
-   case GenRegisterInfo:
-     EmitRegisterInfo(Records, OS);
---- tools/clang/utils/TableGen/TableGen.cpp	2015-09-19 19:30:26.983452195 -0700
-+++ tools/clang/utils/TableGen/TableGen.cpp	2015-09-19 23:12:38.299907988 -0700
-@@ -48,101 +48,99 @@
-   GenClangCommentHTMLTagsProperties,
-   GenClangCommentHTMLNamedCharacterReferences,
-   GenClangCommentCommandInfo,
-   GenClangCommentCommandList,
-   GenArmNeon,
-   GenArmNeonSema,
-   GenArmNeonTest,
-   GenAttrDocs
- };
- 
--namespace {
--cl::opt<ActionType> Action(
--    cl::desc("Action to perform:"),
--    cl::values(
--        clEnumValN(GenClangAttrClasses, "gen-clang-attr-classes",
--                   "Generate clang attribute clases"),
--        clEnumValN(GenClangAttrParserStringSwitches,
--                   "gen-clang-attr-parser-string-switches",
--                   "Generate all parser-related attribute string switches"),
--        clEnumValN(GenClangAttrImpl, "gen-clang-attr-impl",
--                   "Generate clang attribute implementations"),
--        clEnumValN(GenClangAttrList, "gen-clang-attr-list",
--                   "Generate a clang attribute list"),
--        clEnumValN(GenClangAttrPCHRead, "gen-clang-attr-pch-read",
--                   "Generate clang PCH attribute reader"),
--        clEnumValN(GenClangAttrPCHWrite, "gen-clang-attr-pch-write",
--                   "Generate clang PCH attribute writer"),
--        clEnumValN(GenClangAttrHasAttributeImpl,
--                   "gen-clang-attr-has-attribute-impl",
--                   "Generate a clang attribute spelling list"),
--        clEnumValN(GenClangAttrSpellingListIndex,
--                   "gen-clang-attr-spelling-index",
--                   "Generate a clang attribute spelling index"),
--        clEnumValN(GenClangAttrASTVisitor,
--                   "gen-clang-attr-ast-visitor",
--                   "Generate a recursive AST visitor for clang attributes"),
--        clEnumValN(GenClangAttrTemplateInstantiate,
--                   "gen-clang-attr-template-instantiate",
--                   "Generate a clang template instantiate code"),
--        clEnumValN(GenClangAttrParsedAttrList,
--                   "gen-clang-attr-parsed-attr-list",
--                   "Generate a clang parsed attribute list"),
--        clEnumValN(GenClangAttrParsedAttrImpl,
--                   "gen-clang-attr-parsed-attr-impl",
--                   "Generate the clang parsed attribute helpers"),
--        clEnumValN(GenClangAttrParsedAttrKinds,
--                   "gen-clang-attr-parsed-attr-kinds",
--                   "Generate a clang parsed attribute kinds"),
--        clEnumValN(GenClangAttrDump, "gen-clang-attr-dump",
--                   "Generate clang attribute dumper"),
--        clEnumValN(GenClangDiagsDefs, "gen-clang-diags-defs",
--                   "Generate Clang diagnostics definitions"),
--        clEnumValN(GenClangDiagGroups, "gen-clang-diag-groups",
--                   "Generate Clang diagnostic groups"),
--        clEnumValN(GenClangDiagsIndexName, "gen-clang-diags-index-name",
--                   "Generate Clang diagnostic name index"),
--        clEnumValN(GenClangCommentNodes, "gen-clang-comment-nodes",
--                   "Generate Clang AST comment nodes"),
--        clEnumValN(GenClangDeclNodes, "gen-clang-decl-nodes",
--                   "Generate Clang AST declaration nodes"),
--        clEnumValN(GenClangStmtNodes, "gen-clang-stmt-nodes",
--                   "Generate Clang AST statement nodes"),
--        clEnumValN(GenClangSACheckers, "gen-clang-sa-checkers",
--                   "Generate Clang Static Analyzer checkers"),
--        clEnumValN(GenClangCommentHTMLTags, "gen-clang-comment-html-tags",
--                   "Generate efficient matchers for HTML tag "
--                   "names that are used in documentation comments"),
--        clEnumValN(GenClangCommentHTMLTagsProperties,
--                   "gen-clang-comment-html-tags-properties",
--                   "Generate efficient matchers for HTML tag "
--                   "properties"),
--        clEnumValN(GenClangCommentHTMLNamedCharacterReferences,
--                   "gen-clang-comment-html-named-character-references",
--                   "Generate function to translate named character "
--                   "references to UTF-8 sequences"),
--        clEnumValN(GenClangCommentCommandInfo, "gen-clang-comment-command-info",
--                   "Generate command properties for commands that "
--                   "are used in documentation comments"),
--        clEnumValN(GenClangCommentCommandList, "gen-clang-comment-command-list",
--                   "Generate list of commands that are used in "
--                   "documentation comments"),
--        clEnumValN(GenArmNeon, "gen-arm-neon", "Generate arm_neon.h for clang"),
--        clEnumValN(GenArmNeonSema, "gen-arm-neon-sema",
--                   "Generate ARM NEON sema support for clang"),
--        clEnumValN(GenArmNeonTest, "gen-arm-neon-test",
--                   "Generate ARM NEON tests for clang"),
--        clEnumValN(GenAttrDocs, "gen-attr-docs",
--                   "Generate attribute documentation"),
--        clEnumValEnd));
-+static cl::opt<ActionType>
-+Action(cl::desc("Action to perform:"),
-+       cl::values(clEnumValN(GenClangAttrClasses, "gen-clang-attr-classes",
-+                             "Generate clang attribute clases"),
-+                  clEnumValN(GenClangAttrParserStringSwitches,
-+                             "gen-clang-attr-parser-string-switches",
-+                             "Generate all parser-related attribute string switches"),
-+                  clEnumValN(GenClangAttrImpl, "gen-clang-attr-impl",
-+                             "Generate clang attribute implementations"),
-+                  clEnumValN(GenClangAttrList, "gen-clang-attr-list",
-+                             "Generate a clang attribute list"),
-+                  clEnumValN(GenClangAttrPCHRead, "gen-clang-attr-pch-read",
-+                             "Generate clang PCH attribute reader"),
-+                  clEnumValN(GenClangAttrPCHWrite, "gen-clang-attr-pch-write",
-+                             "Generate clang PCH attribute writer"),
-+                  clEnumValN(GenClangAttrHasAttributeImpl,
-+                             "gen-clang-attr-has-attribute-impl",
-+                             "Generate a clang attribute spelling list"),
-+                  clEnumValN(GenClangAttrSpellingListIndex,
-+                             "gen-clang-attr-spelling-index",
-+                             "Generate a clang attribute spelling index"),
-+                  clEnumValN(GenClangAttrASTVisitor,
-+                             "gen-clang-attr-ast-visitor",
-+                             "Generate a recursive AST visitor for clang attributes"),
-+                  clEnumValN(GenClangAttrTemplateInstantiate,
-+                             "gen-clang-attr-template-instantiate",
-+                             "Generate a clang template instantiate code"),
-+                  clEnumValN(GenClangAttrParsedAttrList,
-+                             "gen-clang-attr-parsed-attr-list",
-+                             "Generate a clang parsed attribute list"),
-+                  clEnumValN(GenClangAttrParsedAttrImpl,
-+                             "gen-clang-attr-parsed-attr-impl",
-+                             "Generate the clang parsed attribute helpers"),
-+                  clEnumValN(GenClangAttrParsedAttrKinds,
-+                             "gen-clang-attr-parsed-attr-kinds",
-+                             "Generate a clang parsed attribute kinds"),
-+                  clEnumValN(GenClangAttrDump, "gen-clang-attr-dump",
-+                             "Generate clang attribute dumper"),
-+                  clEnumValN(GenClangDiagsDefs, "gen-clang-diags-defs",
-+                             "Generate Clang diagnostics definitions"),
-+                  clEnumValN(GenClangDiagGroups, "gen-clang-diag-groups",
-+                             "Generate Clang diagnostic groups"),
-+                  clEnumValN(GenClangDiagsIndexName, "gen-clang-diags-index-name",
-+                             "Generate Clang diagnostic name index"),
-+                  clEnumValN(GenClangCommentNodes, "gen-clang-comment-nodes",
-+                             "Generate Clang AST comment nodes"),
-+                  clEnumValN(GenClangDeclNodes, "gen-clang-decl-nodes",
-+                             "Generate Clang AST declaration nodes"),
-+                  clEnumValN(GenClangStmtNodes, "gen-clang-stmt-nodes",
-+                             "Generate Clang AST statement nodes"),
-+                  clEnumValN(GenClangSACheckers, "gen-clang-sa-checkers",
-+                             "Generate Clang Static Analyzer checkers"),
-+                  clEnumValN(GenClangCommentHTMLTags, "gen-clang-comment-html-tags",
-+                             "Generate efficient matchers for HTML tag "
-+                             "names that are used in documentation comments"),
-+                  clEnumValN(GenClangCommentHTMLTagsProperties,
-+                             "gen-clang-comment-html-tags-properties",
-+                             "Generate efficient matchers for HTML tag "
-+                             "properties"),
-+                  clEnumValN(GenClangCommentHTMLNamedCharacterReferences,
-+                             "gen-clang-comment-html-named-character-references",
-+                             "Generate function to translate named character "
-+                             "references to UTF-8 sequences"),
-+                  clEnumValN(GenClangCommentCommandInfo, "gen-clang-comment-command-info",
-+                             "Generate command properties for commands that "
-+                             "are used in documentation comments"),
-+                  clEnumValN(GenClangCommentCommandList, "gen-clang-comment-command-list",
-+                             "Generate list of commands that are used in "
-+                             "documentation comments"),
-+                  clEnumValN(GenArmNeon, "gen-arm-neon", "Generate arm_neon.h for clang"),
-+                  clEnumValN(GenArmNeonSema, "gen-arm-neon-sema",
-+                             "Generate ARM NEON sema support for clang"),
-+                  clEnumValN(GenArmNeonTest, "gen-arm-neon-test",
-+                             "Generate ARM NEON tests for clang"),
-+                  clEnumValN(GenAttrDocs, "gen-attr-docs",
-+                             "Generate attribute documentation"),
-+                  clEnumValEnd));
- 
--cl::opt<std::string>
-+static cl::opt<std::string>
- ClangComponent("clang-component",
-                cl::desc("Only use warnings from specified component"),
-                cl::value_desc("component"), cl::Hidden);
- 
- bool ClangTableGenMain(raw_ostream &OS, RecordKeeper &Records) {
-   switch (Action) {
-   case GenClangAttrClasses:
-     EmitClangAttrClass(Records, OS);
-     break;
-   case GenClangAttrParserStringSwitches:
-@@ -230,21 +228,20 @@
-   case GenArmNeonTest:
-     EmitNeonTest(Records, OS);
-     break;
-   case GenAttrDocs:
-     EmitClangAttrDocs(Records, OS);
-     break;
-   }
- 
-   return false;
- }
--}
- 
- int main(int argc, char **argv) {
-   sys::PrintStackTraceOnErrorSignal();
-   PrettyStackTraceProgram X(argc, argv);
-   cl::ParseCommandLineOptions(argc, argv);
- 
-   return TableGenMain(argv[0], &ClangTableGenMain);
- }
- 
- #ifdef __has_feature
---- lib/IR/LegacyPassManager.cpp	2015-01-28 09:39:35.000000000 -0800
-+++ lib/IR/LegacyPassManager.cpp	2015-10-05 11:01:32.789436446 -0700
-@@ -40,15 +40,18 @@
- // pass name to be printed before it executes.
- //
- 
--namespace {
- // Different debug levels that can be enabled...
- enum PassDebugLevel {
--  Disabled, Arguments, Structure, Executions, Details
-+  Disabled,
-+  Arguments,
-+  Structure,
-+  Executions,
-+  Details
- };
--}
- 
- static cl::opt<enum PassDebugLevel>
--PassDebugging("debug-pass", cl::Hidden,
-+PassDebugging("debug-pass",
-+              cl::Hidden,
-                   cl::desc("Print PassManager debugging information"),
-                   cl::values(
-   clEnumVal(Disabled  , "disable debug output"),
-@@ -58,36 +61,44 @@
-   clEnumVal(Details   , "print pass details when it is executed"),
-                              clEnumValEnd));
- 
--namespace {
--typedef llvm::cl::list<const llvm::PassInfo *, bool, PassNameParser>
--PassOptionList;
--}
--
- // Print IR out before/after specified passes.
--static PassOptionList
--PrintBefore("print-before",
--            llvm::cl::desc("Print IR before specified passes"),
--            cl::Hidden);
--
--static PassOptionList
--PrintAfter("print-after",
--           llvm::cl::desc("Print IR after specified passes"),
--           cl::Hidden);
-+static llvm::cl::list<const llvm::PassInfo *, bool, PassNameParser>
-+PrintBefore(cl::Prefix, "print-before",
-+            cl::desc("Print IR before specified passes"),
-+            cl::value_desc("Print IR before specified passes"),
-+            cl::Hidden,
-+            cl::ZeroOrMore);
-+
-+static llvm::cl::list<const llvm::PassInfo *, bool, PassNameParser>
-+PrintAfter(cl::Prefix, "print-after",
-+           cl::desc("Print IR after specified passes"),
-+           cl::value_desc("Print IR after specified passes"),
-+           cl::Hidden,
-+           cl::ZeroOrMore);
- 
- static cl::opt<bool>
--PrintBeforeAll("print-before-all",
-+PrintBeforeAll(cl::NormalFormatting, "print-before-all",
-                llvm::cl::desc("Print IR before each pass"),
-+               llvm::cl::value_desc("Print IR before each pass"),
-+               cl::Hidden,
-+               cl::Optional,
-                cl::init(false));
-+
- static cl::opt<bool>
--PrintAfterAll("print-after-all",
-+PrintAfterAll(cl::NormalFormatting, "print-after-all",
-               llvm::cl::desc("Print IR after each pass"),
-+              llvm::cl::value_desc("Print IR after each pass"),
-+              cl::Hidden,
-+              cl::Optional,
-               cl::init(false));
- 
- /// This is a helper to determine whether to print IR before or
- /// after a pass.
- 
--static bool ShouldPrintBeforeOrAfterPass(const PassInfo *PI,
--                                         PassOptionList &PassesToPrint) {
-+static bool
-+ShouldPrintBeforeOrAfterPass(const PassInfo *PI,
-+                             llvm::cl::list<const llvm::PassInfo *, bool,
-+                                            PassNameParser> &PassesToPrint) {
-   for (unsigned i = 0, ie = PassesToPrint.size(); i < ie; ++i) {
-     const llvm::PassInfo *PassInf = PassesToPrint[i];
-     if (PassInf)
---- lib/Support/CommandLine.cpp	2015-01-13 11:14:20.000000000 -0800
-+++ lib/Support/CommandLine.cpp	2016-01-19 10:13:33.212967353 -0800
-@@ -41,6 +41,8 @@
- 
- #define DEBUG_TYPE "commandline"
- 
-+#include <iostream>
-+
- //===----------------------------------------------------------------------===//
- // Template instantiations and anchors.
- //
-@@ -85,7 +87,7 @@
- 
- // Globals for name and overview of program.  Program name is not a string to
- // avoid static ctor/dtor issues.
--static char ProgramName[80] = "<premain>";
-+static std::string ProgramName("<premain>");
- static const char *ProgramOverview = nullptr;
- 
- // This collects additional help to be printed.
-@@ -102,14 +104,14 @@
- 
- /// RegisteredOptionList - This is the list of the command line options that
- /// have statically constructed themselves.
--static Option *RegisteredOptionList = nullptr;
-+Option *Option::RegisteredOptionList = nullptr;
- 
- void Option::addArgument() {
-   assert(!NextRegistered && "argument multiply registered!");
-+  Option *O = dynamic_cast<Option*>(this);
-+  assert(O && "Cannot dynamic_cast to correct type!");
- 
--  NextRegistered = RegisteredOptionList;
--  RegisteredOptionList = this;
--  MarkOptionsChanged();
-+  Option::registerOption(O);
- }
- 
- void Option::removeArgument() {
-@@ -149,24 +151,26 @@
- 
- /// GetOptionInfo - Scan the list of registered options, turning them into data
- /// structures that are easier to handle.
--static void GetOptionInfo(SmallVectorImpl<Option *> &PositionalOpts,
--                          SmallVectorImpl<Option *> &SinkOpts,
-+static void GetOptionInfo(std::vector<Option *> &PositionalOpts,
-+                          std::vector<Option *> &SinkOpts,
-                           StringMap<Option *> &OptionsMap) {
-   bool HadErrors = false;
--  SmallVector<const char *, 16> OptionNames;
-+  std::vector<const char *> OptionNames;
-   Option *CAOpt = nullptr; // The ConsumeAfter option if it exists.
--  for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
-+  for (Option *O = Option::getRegisteredOptionList(); O;
-+       O = O->getNextRegisteredOption()) {
-     // If this option wants to handle multiple option names, get the full set.
-     // This handles enum options like "-O1 -O2" etc.
-     O->getExtraOptionNames(OptionNames);
--    if (O->ArgStr[0])
-+
-+    if (O->ArgStr && *O->ArgStr)
-       OptionNames.push_back(O->ArgStr);
- 
-     // Handle named options.
-     for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
-       // Add argument to the argument map!
-       if (!OptionsMap.insert(std::make_pair(OptionNames[i], O)).second) {
--        errs() << ProgramName << ": CommandLine Error: Option '"
-+        errs() << ProgramName.c_str() << ": CommandLine Error: Option '"
-                << OptionNames[i] << "' registered more than once!\n";
-         HadErrors = true;
-       }
-@@ -201,6 +205,24 @@
-     report_fatal_error("inconsistency in registered CommandLine options");
- }
- 
-+/// HandleSpecialPrefixOptions - certain options need special handling
-+/// of their Argyment/Value pair, because there will be no space separator
-+/// between the two. For example -O<N> (optimization level).
-+static void HandleSpecialPrefixOptions(StringRef &ArgName, StringRef &Value) {
-+  if (ArgName.empty())
-+    return;
-+
-+  char AN = ArgName.front();
-+  switch (AN) {
-+  default:
-+    break;
-+  case 'O':
-+    Value = ArgName.substr(1, 1);
-+    ArgName = ArgName.substr(0, 1);
-+    break;
-+  }
-+}
-+
- /// LookupOption - Lookup the option specified by the specified option on the
- /// command line.  If there is a value specified (after an equal sign) return
- /// that as well.  This assumes that leading dashes have already been stripped.
-@@ -210,12 +232,35 @@
-   if (Arg.empty())
-     return nullptr;
- 
-+  HandleSpecialPrefixOptions(Arg, Value);
-+
-   size_t EqualPos = Arg.find('=');
- 
-   // If we have an equals sign, remember the value.
-   if (EqualPos == StringRef::npos) {
-+    StringRef InputFile;
-+
-     // Look up the option.
-     StringMap<Option *>::const_iterator I = OptionsMap.find(Arg);
-+
-+    // TableGen
-+    if (I == OptionsMap.end()) {
-+      InputFile = "<input file>";
-+      I = OptionsMap.find(InputFile);
-+    }
-+
-+    // lli && llc
-+    if (I == OptionsMap.end()) {
-+      InputFile = "<input bitcode>";
-+      I = OptionsMap.find(InputFile);
-+    }
-+
-+    // opt
-+    if (I == OptionsMap.end()) {
-+      InputFile = "<input bitcode file>";
-+      I = OptionsMap.find(InputFile);
-+    }
-+
-     return I != OptionsMap.end() ? I->second : nullptr;
-   }
- 
-@@ -254,7 +299,7 @@
-                                            ie = OptionsMap.end();
-        it != ie; ++it) {
-     Option *O = it->second;
--    SmallVector<const char *, 16> OptionNames;
-+    std::vector<const char *> OptionNames;
-     O->getExtraOptionNames(OptionNames);
-     if (O->ArgStr[0])
-       OptionNames.push_back(O->ArgStr);
-@@ -322,9 +367,11 @@
-   // Enforce value requirements
-   switch (Handler->getValueExpectedFlag()) {
-   case ValueRequired:
--    if (!Value.data()) { // No value specified?
-+    if (Value.empty()) { // No value specified?
-       if (i + 1 >= argc)
--        return Handler->error("requires a value!");
-+        return
-+          Handler->error("argument requires a value but none was provided!");
-+
-       // Steal the next argument, like for '-o filename'
-       assert(argv && "null check");
-       Value = argv[++i];
-@@ -335,11 +382,17 @@
-       return Handler->error("multi-valued option specified"
-                             " with ValueDisallowed modifier!");
- 
--    if (Value.data())
-+    if (!Value.empty())
-       return Handler->error("does not allow a value! '" + Twine(Value) +
-                             "' specified.");
-     break;
-   case ValueOptional:
-+  case ValuePositionalNoArgs:
-+    break;
-+  case ValuePositionalWithArgs:
-+    break;
-+  default:
-+    return Handler->error("Unknown/invalid Option type!");
-     break;
-   }
- 
-@@ -373,7 +426,15 @@
- 
- static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
-   int Dummy = i;
--  return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
-+  bool R = ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
-+  return R;
-+}
-+
-+static bool ProvidePositionalOptionWithArgs(Option *Handler, StringRef Arg,
-+                                            int i, unsigned &ValNo,
-+                                            unsigned &NumPositionsRequired) {
-+  // FIXME: IMPLEMENT
-+  return false;
- }
- 
- // Option predicates...
-@@ -416,7 +477,7 @@
- /// see if this is a prefix or grouped option.  If so, split arg into output an
- /// Arg/Value pair and return the Option to parse it with.
- static Option *
--HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
-+HandlePrefixedOrGroupedOption(std::string &Arg, std::string &Value,
-                               bool &ErrorParsing,
-                               const StringMap<Option *> &OptionsMap) {
-   if (Arg.size() == 1)
-@@ -465,7 +526,10 @@
- 
- static bool RequiresValue(const Option *O) {
-   return O->getNumOccurrencesFlag() == cl::Required ||
--         O->getNumOccurrencesFlag() == cl::OneOrMore;
-+         O->getNumOccurrencesFlag() == cl::OneOrMore ||
-+         O->getValueExpectedFlag() == cl::ValueRequired ||
-+         O->getValueExpectedFlag() == cl::ValuePositionalNoArgs ||
-+         O->getValueExpectedFlag() == cl::ValuePositionalWithArgs;
- }
- 
- static bool EatsUnboundedNumberOfValues(const Option *O) {
-@@ -480,9 +544,9 @@
- static bool isGNUSpecial(char C) { return strchr("\\\"\' ", C); }
- 
- void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
--                                SmallVectorImpl<const char *> &NewArgv,
-+                                std::vector<const char *> &NewArgv,
-                                 bool MarkEOLs) {
--  SmallString<128> Token;
-+  SmallString<PATH_MAX> Token;
-   for (size_t I = 0, E = Src.size(); I != E; ++I) {
-     // Consume runs of whitespace.
-     if (Token.empty()) {
-@@ -556,7 +620,7 @@
- ///    consumed in this case.
- ///
- ///  * Otherwise, backslashes are interpreted literally.
--static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
-+static size_t parseBackslash(StringRef Src, size_t I, SmallString<256> &Token) {
-   size_t E = Src.size();
-   int BackslashCount = 0;
-   // Skip the backslashes.
-@@ -578,9 +642,9 @@
- }
- 
- void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
--                                    SmallVectorImpl<const char *> &NewArgv,
-+                                    std::vector<const char *> &NewArgv,
-                                     bool MarkEOLs) {
--  SmallString<128> Token;
-+  SmallString<256> Token;
- 
-   // This is a small state machine to consume characters until it reaches the
-   // end of the source string.
-@@ -657,7 +721,7 @@
- 
- static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
-                                TokenizerCallback Tokenizer,
--                               SmallVectorImpl<const char *> &NewArgv,
-+                               std::vector<const char *> &NewArgv,
-                                bool MarkEOLs = false) {
-   ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
-       MemoryBuffer::getFile(FName);
-@@ -684,7 +748,7 @@
- /// \brief Expand response files on a command line recursively using the given
- /// StringSaver and tokenization strategy.
- bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
--                             SmallVectorImpl<const char *> &Argv,
-+                             std::vector<const char *> &Argv,
-                              bool MarkEOLs) {
-   unsigned RspFiles = 0;
-   bool AllExpanded = true;
-@@ -711,7 +775,7 @@
-     // contents.  Nested response files are expanded in subsequent iterations.
-     // FIXME: If a nested response file uses a relative path, is it relative to
-     // the cwd of the process or the response file?
--    SmallVector<const char *, 0> ExpandedArgv;
-+    std::vector<const char *> ExpandedArgv;
-     if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv,
-                             MarkEOLs)) {
-       // We couldn't read this file, so we leave it in the argument stream and
-@@ -764,7 +828,7 @@
- 
-   // Get program's "name", which we wouldn't know without the caller
-   // telling us.
--  SmallVector<const char *, 20> newArgv;
-+  std::vector<const char *> newArgv;
-   StrDupSaver Saver;
-   newArgv.push_back(Saver.SaveString(progName));
- 
-@@ -778,27 +842,25 @@
- void cl::ParseCommandLineOptions(int argc, const char *const *argv,
-                                  const char *Overview) {
-   // Process all registered options.
--  SmallVector<Option *, 4> PositionalOpts;
--  SmallVector<Option *, 4> SinkOpts;
-+  std::vector<Option*> PositionalOpts;
-+  std::vector<Option*> SinkOpts;
-   StringMap<Option *> Opts;
-   GetOptionInfo(PositionalOpts, SinkOpts, Opts);
- 
-   assert((!Opts.empty() || !PositionalOpts.empty()) && "No options specified!");
- 
-   // Expand response files.
--  SmallVector<const char *, 20> newArgv;
-+  std::vector<const char*> newArgv;
-+
-   for (int i = 0; i != argc; ++i)
-     newArgv.push_back(argv[i]);
-+
-   StrDupSaver Saver;
-   ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
-   argv = &newArgv[0];
-   argc = static_cast<int>(newArgv.size());
- 
--  // Copy the program name into ProgName, making sure not to overflow it.
--  StringRef ProgName = sys::path::filename(argv[0]);
--  size_t Len = std::min(ProgName.size(), size_t(79));
--  memcpy(ProgramName, ProgName.data(), Len);
--  ProgramName[Len] = '\0';
-+  ProgramName = sys::path::filename(argv[0]).str();
- 
-   ProgramOverview = Overview;
-   bool ErrorParsing = false;
-@@ -810,6 +872,7 @@
-   bool HasUnlimitedPositionals = false;
- 
-   Option *ConsumeAfterOpt = nullptr;
-+
-   if (!PositionalOpts.empty()) {
-     if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
-       assert(PositionalOpts.size() > 1 &&
-@@ -819,8 +882,7 @@
- 
-     // Calculate how many positional values are _required_.
-     bool UnboundedFound = false;
--    for (size_t i = ConsumeAfterOpt ? 1 : 0, e = PositionalOpts.size(); i != e;
--         ++i) {
-+    for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
-       Option *Opt = PositionalOpts[i];
-       if (RequiresValue(Opt))
-         ++NumPositionalRequired;
-@@ -844,13 +906,14 @@
-       }
-       UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
-     }
-+
-     HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
-   }
- 
-   // PositionalVals - A vector of "positional" arguments we accumulate into
-   // the process at the end.
-   //
--  SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
-+  std::vector<std::pair<StringRef, unsigned> > PositionalVals;
- 
-   // If the program has named positional arguments, and the name has been run
-   // across, keep track of which positional argument was named.  Otherwise put
-@@ -862,39 +925,25 @@
-   for (int i = 1; i < argc; ++i) {
-     Option *Handler = nullptr;
-     Option *NearestHandler = nullptr;
-+    Option *PrefixOrGroupHandler = nullptr;
-     std::string NearestHandlerString;
--    StringRef Value;
-+    StringRef Value = "";
-     StringRef ArgName = "";
- 
--    // If the option list changed, this means that some command line
--    // option has just been registered or deregistered.  This can occur in
--    // response to things like -load, etc.  If this happens, rescan the options.
--    if (OptionListChanged) {
--      PositionalOpts.clear();
--      SinkOpts.clear();
--      Opts.clear();
--      GetOptionInfo(PositionalOpts, SinkOpts, Opts);
--      OptionListChanged = false;
--    }
--
-     // Check to see if this is a positional argument.  This argument is
-     // considered to be positional if it doesn't start with '-', if it is "-"
-     // itself, or if we have seen "--" already.
-     //
--    if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
--      // Positional argument!
--      if (ActivePositionalArg) {
--        ProvidePositionalOption(ActivePositionalArg, argv[i], i);
--        continue; // We are done!
--      }
--
-+    if (((argv[i][0] != '-') && (argv[i][1] != '\0')) ||
-+        ((argv[i][0] == '-') && (argv[i][1] == '\0')) || DashDashFound) {
-       if (!PositionalOpts.empty()) {
-         PositionalVals.push_back(std::make_pair(argv[i], i));
- 
-         // All of the positional arguments have been fulfulled, give the rest to
-         // the consume after option... if it's specified...
-         //
--        if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
-+        if ((PositionalVals.size() >= NumPositionalRequired) &&
-+            ConsumeAfterOpt) {
-           for (++i; i < argc; ++i)
-             PositionalVals.push_back(std::make_pair(argv[i], i));
-           break; // Handle outside of the argument processing loop...
-@@ -913,6 +962,7 @@
-       // option is another positional argument.  If so, treat it as an argument,
-       // otherwise feed it to the eating positional.
-       ArgName = argv[i] + 1;
-+
-       // Eat leading dashes.
-       while (!ArgName.empty() && ArgName[0] == '-')
-         ArgName = ArgName.substr(1);
-@@ -924,17 +974,32 @@
-       }
- 
-     } else { // We start with a '-', must be an argument.
--      ArgName = argv[i] + 1;
-+      // ArgName = i == (argc - 1) ? argv[i] : argv[i] + 1;
-+      ArgName = argv[i];
-+
-       // Eat leading dashes.
-       while (!ArgName.empty() && ArgName[0] == '-')
-         ArgName = ArgName.substr(1);
- 
-       Handler = LookupOption(ArgName, Value, Opts);
--
--      // Check to see if this "option" is really a prefixed or grouped argument.
--      if (!Handler)
--        Handler =
--            HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing, Opts);
-+      if (Handler) {
-+        enum FormattingFlags FF = Handler->getFormattingFlag();
-+        if ((FF == llvm::cl::Prefix) || (FF == llvm::cl::Grouping)) {
-+          if (Value.empty())
-+            Value = argv[++i];
-+
-+          std::string SA = ArgName.str();
-+          std::string SV = Value.str();
-+          SA.append(SV);
-+
-+          // Check to see if this "option" is really a prefixed or
-+          // grouped argument.
-+          PrefixOrGroupHandler =
-+            HandlePrefixedOrGroupedOption(SA, SV, ErrorParsing, Opts);
-+          if (PrefixOrGroupHandler)
-+            Handler = PrefixOrGroupHandler;
-+        }
-+      }
- 
-       // Otherwise, look for the closest available option to report to the user
-       // in the upcoming error.
-@@ -945,22 +1010,23 @@
- 
-     if (!Handler) {
-       if (SinkOpts.empty()) {
--        errs() << ProgramName << ": Unknown command line argument '" << argv[i]
--               << "'.  Try: '" << argv[0] << " -help'\n";
-+        errs() << ProgramName.c_str()
-+          << ": Unknown command line argument '" << argv[i]
-+          << "'.  Try: '" << argv[0] << " -help'\n";
- 
-         if (NearestHandler) {
-           // If we know a near match, report it as well.
--          errs() << ProgramName << ": Did you mean '-" << NearestHandlerString
--                 << "'?\n";
-+          errs() << ProgramName.c_str()
-+            << ": Did you mean '-" << NearestHandlerString << "'?\n";
-         }
- 
-         ErrorParsing = true;
-       } else {
--        for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(),
--                                                 E = SinkOpts.end();
--             I != E; ++I)
-+        for (std::vector<Option *>::iterator I = SinkOpts.begin(),
-+             E = SinkOpts.end(); I != E; ++I)
-           (*I)->addOccurrence(i, "", argv[i]);
-       }
-+
-       continue;
-     }
- 
-@@ -974,50 +1040,77 @@
- 
-   // Check and handle positional arguments now...
-   if (NumPositionalRequired > PositionalVals.size()) {
--    errs() << ProgramName
--           << ": Not enough positional command line arguments specified!\n"
--           << "Must specify at least " << NumPositionalRequired
--           << " positional arguments: See: " << argv[0] << " -help\n";
-+    errs() << ProgramName.c_str()
-+      << ": Not enough positional command line arguments specified!\n"
-+      << "Must specify at least " << NumPositionalRequired
-+      << " positional arguments: See: " << argv[0] << " -help\n";
- 
-     ErrorParsing = true;
-   } else if (!HasUnlimitedPositionals &&
-              PositionalVals.size() > PositionalOpts.size()) {
--    errs() << ProgramName << ": Too many positional arguments specified!\n"
--           << "Can specify at most " << PositionalOpts.size()
--           << " positional arguments: See: " << argv[0] << " -help\n";
-+    errs() << ProgramName.c_str()
-+      << ": Too many positional arguments specified!\n"
-+      << "Can specify at most " << PositionalOpts.size()
-+      << " positional arguments: See: " << argv[0] << " -help\n";
-     ErrorParsing = true;
- 
-   } else if (!ConsumeAfterOpt) {
-     // Positional args have already been handled if ConsumeAfter is specified.
--    unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
-+    unsigned ValNo = 0;
-+    unsigned NumVals = static_cast<unsigned>(PositionalVals.size());
-     for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
--      if (RequiresValue(PositionalOpts[i])) {
--        ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
-+      Option *PO = PositionalOpts[i];
-+      if (RequiresValue(PO)) {
-+        ProvidePositionalOption(PO, PositionalVals[ValNo].first,
-                                 PositionalVals[ValNo].second);
-         ValNo++;
-         --NumPositionalRequired; // We fulfilled our duty...
-       }
- 
-+      enum llvm::cl::ValueExpected VE = PO->getValueExpectedFlag();
-+
-+      // If it's a positional argument, provide it.
-+      if ((NumVals - ValNo) > NumPositionalRequired) {
-+        if (VE == llvm::cl::ValuePositionalNoArgs) {
-+          ProvidePositionalOption(PO, PositionalVals[ValNo].first,
-+                                  PositionalVals[ValNo].second);
-+          ++ValNo;
-+          --NumPositionalRequired;
-+          continue;
-+        } else if (VE == llvm::cl::ValuePositionalWithArgs) {
-+          ProvidePositionalOptionWithArgs(PO, PositionalVals[ValNo].first,
-+                                          PositionalVals[ValNo].second,
-+                                          ValNo,
-+                                          NumPositionalRequired);
-+          continue;
-+        }
-+      }
-+
-       // If we _can_ give this option more arguments, do so now, as long as we
-       // do not give it values that others need.  'Done' controls whether the
-       // option even _WANTS_ any more.
-       //
--      bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
--      while (NumVals - ValNo > NumPositionalRequired && !Done) {
--        switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
-+      bool Done =
-+        ((PO->getNumOccurrencesFlag() == cl::Required) &&
-+         (VE != llvm::cl::ValuePositionalNoArgs));
-+
-+      while (((NumVals - ValNo) > NumPositionalRequired)  && !Done) {
-+        switch (PO->getNumOccurrencesFlag()) {
-         case cl::Optional:
-           Done = true; // Optional arguments want _at most_ one value
-         // FALL THROUGH
-+          break;
-         case cl::ZeroOrMore: // Zero or more will take all they can get...
-         case cl::OneOrMore:  // One or more will take all they can get...
--          ProvidePositionalOption(PositionalOpts[i],
--                                  PositionalVals[ValNo].first,
-+          ProvidePositionalOption(PO, PositionalVals[ValNo].first,
-                                   PositionalVals[ValNo].second);
-           ValNo++;
-           break;
-         default:
--          llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
--                           "positional argument processing!");
-+          assert(0 && "Internal Compiler Error: "
-+                 "unexpected NumOccurrences flag "
-+                 "in positional argument processing!");
-+          break;
-         }
-       }
-     }
-@@ -1029,7 +1122,7 @@
-         ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
-                                                 PositionalVals[ValNo].first,
-                                                 PositionalVals[ValNo].second);
--        ValNo++;
-+        ++ValNo;
-       }
- 
-     // Handle the case where there is just one positional option, and it's
-@@ -1041,7 +1134,7 @@
-       ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
-                                               PositionalVals[ValNo].first,
-                                               PositionalVals[ValNo].second);
--      ValNo++;
-+      ++ValNo;
-     }
- 
-     // Handle over all of the rest of the arguments to the
-@@ -1061,7 +1154,7 @@
-         Opt.second->error("must be specified at least once!");
-         ErrorParsing = true;
-       }
--    // Fall through
-+      break;
-     default:
-       break;
-     }
-@@ -1095,7 +1188,7 @@
-   if (ArgName.empty())
-     errs() << HelpStr; // Be nice for positional arguments
-   else
--    errs() << ProgramName << ": for the -" << ArgName;
-+    errs() << ProgramName.c_str() << ": for the -" << ArgName;
- 
-   errs() << " option: " << Message << "\n";
-   return true;
-@@ -1106,7 +1199,9 @@
-   if (!MultiArg)
-     NumOccurrences++; // Increment the number of times we have been seen
- 
--  switch (getNumOccurrencesFlag()) {
-+  llvm::cl::NumOccurrencesFlag NOF = getNumOccurrencesFlag();
-+
-+  switch (NOF) {
-   case Optional:
-     if (NumOccurrences > 1)
-       return error("may only occur zero or one times!", ArgName);
-@@ -1121,7 +1216,11 @@
-     break;
-   }
- 
--  return handleOccurrence(pos, ArgName, Value);
-+  std::string SAN = ArgName;
-+  std::string SV = Value;
-+
-+  bool R = handleOccurrence(pos, SAN.c_str(), SV.c_str());
-+  return R;
- }
- 
- // getValueStr - Get the value description string, using "DefaultMsg" if nothing
-@@ -1402,11 +1501,12 @@
- PRINT_OPT_DIFF(float)
- PRINT_OPT_DIFF(char)
- 
--void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
-+void parser<std::string>::printOptionDiff(const Option &O,
-+                                          const std::string &V,
-                                           OptionValue<std::string> D,
-                                           size_t GlobalWidth) const {
-   printOptionName(O, GlobalWidth);
--  outs() << "= " << V;
-+  outs() << "= " << V.c_str();
-   size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
-   outs().indent(NumSpaces) << " (default: ";
-   if (D.hasValue())
-@@ -1427,20 +1527,22 @@
- // -help and -help-hidden option implementation
- //
- 
--static int OptNameCompare(const void *LHS, const void *RHS) {
--  typedef std::pair<const char *, Option *> pair_ty;
--
--  return strcmp(((const pair_ty *)LHS)->first, ((const pair_ty *)RHS)->first);
--}
-+template<typename Ty>
-+struct OptNameCompare : public std::binary_function<Ty, Ty, bool> {
-+  inline bool operator()(const Ty& LHS, const Ty& RHS) const {
-+    return std::strcmp(LHS.first, RHS.first) <= 0;
-+  }
-+};
- 
- // Copy Options into a vector so we can sort them as we like.
- static void sortOpts(StringMap<Option *> &OptMap,
--                     SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
-+                     std::vector<std::pair<const char*, Option*> > &Opts,
-                      bool ShowHidden) {
-   SmallPtrSet<Option *, 128> OptionSet; // Duplicate option detection.
- 
-   for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
-        I != E; ++I) {
-+
-     // Ignore really-hidden options.
-     if (I->second->getOptionHiddenFlag() == ReallyHidden)
-       continue;
-@@ -1453,12 +1555,13 @@
-     if (!OptionSet.insert(I->second).second)
-       continue;
- 
--    Opts.push_back(
--        std::pair<const char *, Option *>(I->getKey().data(), I->second));
-+    std::pair<const char*, Option*> KVP(I->getKey().data(), I->second);
-+    Opts.push_back(KVP);
-   }
- 
-   // Sort the options list alphabetically.
--  qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
-+  OptNameCompare<std::pair<const char*, Option*> >  ONC;
-+  std::sort(Opts.begin(), Opts.end(), ONC);
- }
- 
- namespace {
-@@ -1466,8 +1569,9 @@
- class HelpPrinter {
- protected:
-   const bool ShowHidden;
--  typedef SmallVector<std::pair<const char *, Option *>, 128>
-+  typedef std::vector<std::pair<const char *, Option *> >
-       StrOptionPairVector;
-+
-   // Print the options. Opts is assumed to be alphabetically sorted.
-   virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
-     for (size_t i = 0, e = Opts.size(); i != e; ++i)
-@@ -1484,8 +1588,8 @@
-       return;
- 
-     // Get all the options.
--    SmallVector<Option *, 4> PositionalOpts;
--    SmallVector<Option *, 4> SinkOpts;
-+    std::vector<Option *> PositionalOpts;
-+    std::vector<Option *> SinkOpts;
-     StringMap<Option *> OptMap;
-     GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
- 
-@@ -1495,7 +1599,7 @@
-     if (ProgramOverview)
-       outs() << "OVERVIEW: " << ProgramOverview << "\n";
- 
--    outs() << "USAGE: " << ProgramName << " [options]";
-+    outs() << "USAGE: " << ProgramName.c_str() << " [options]";
- 
-     // Print out the positional options.
-     Option *CAOpt = nullptr; // The cl::ConsumeAfter option, if it exists...
-@@ -1710,12 +1814,12 @@
-     return;
- 
-   // Get all the options.
--  SmallVector<Option *, 4> PositionalOpts;
--  SmallVector<Option *, 4> SinkOpts;
-+  std::vector<Option *> PositionalOpts;
-+  std::vector<Option *> SinkOpts;
-   StringMap<Option *> OptMap;
-   GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
- 
--  SmallVector<std::pair<const char *, Option *>, 128> Opts;
-+  std::vector<std::pair<const char *, Option *> > Opts;
-   sortOpts(OptMap, Opts, /*ShowHidden*/ true);
- 
-   // Compute the maximum argument length...
-@@ -1825,8 +1929,8 @@
- 
- void cl::getRegisteredOptions(StringMap<Option *> &Map) {
-   // Get all the options.
--  SmallVector<Option *, 4> PositionalOpts; // NOT USED
--  SmallVector<Option *, 4> SinkOpts; // NOT USED
-+  std::vector<Option *> PositionalOpts; // NOT USED
-+  std::vector<Option *> SinkOpts; // NOT USED
-   assert(Map.size() == 0 && "StringMap must be empty");
-   GetOptionInfo(PositionalOpts, SinkOpts, Map);
-   return;
---- lib/Support/PluginLoader.cpp	2012-12-03 08:50:05.000000000 -0800
-+++ lib/Support/PluginLoader.cpp	2016-01-24 11:02:33.000000000 -0800
-@@ -34,6 +34,21 @@
-   }
- }
- 
-+bool PluginLoader::operator==(const std::string &Filename) const {
-+  sys::SmartScopedLock<true> Lock(*PluginsLock);
-+  for (std::vector<std::string>::const_iterator I = Plugins->begin(),
-+       E = Plugins->end(); I != E; ++I) {
-+    if (*I == Filename)
-+      return true;
-+  }
-+
-+  return false;
-+}
-+
-+bool PluginLoader::operator!=(const std::string &Filename) const {
-+  return !this->operator==(Filename);
-+}
-+
- unsigned PluginLoader::getNumPlugins() {
-   sys::SmartScopedLock<true> Lock(*PluginsLock);
-   return Plugins.isConstructed() ? Plugins->size() : 0;
---- include/llvm/Support/CommandLine.h	2015-01-13 11:14:20.000000000 -0800
-+++ include/llvm/Support/CommandLine.h	2016-01-19 11:56:32.087336770 -0800
-@@ -24,6 +24,7 @@
- #include "llvm/ADT/StringMap.h"
- #include "llvm/ADT/Twine.h"
- #include "llvm/Support/Compiler.h"
-+#include "llvm/Support/raw_ostream.h"
- #include <cassert>
- #include <climits>
- #include <cstdarg>
-@@ -97,9 +98,11 @@
- 
- enum ValueExpected { // Is a value required for the option?
-   // zero reserved for the unspecified value
--  ValueOptional = 0x01,  // The value can appear... or not
--  ValueRequired = 0x02,  // The value is required to appear!
--  ValueDisallowed = 0x03 // A value may not be specified (for flags)
-+  ValueOptional = 0x01,           // The value can appear... or not
-+  ValueRequired = 0x02,           // The value is required to appear!
-+  ValueDisallowed = 0x03,         // A value may not be specified (for flags)
-+  ValuePositionalNoArgs = 0x04,   // Positional Argument, no additional args
-+  ValuePositionalWithArgs = 0x05  // Positional Argument, with additional args
- };
- 
- enum OptionHidden {   // Control whether -help shows this option
-@@ -137,6 +140,36 @@
- };
- 
- //===----------------------------------------------------------------------===//
-+// Generic Filename Locations
-+//
-+struct GenericFilenameLocation {
-+  GenericFilenameLocation() : Value("") { }
-+  GenericFilenameLocation(const std::string &S) : Value(S) { }
-+
-+  void operator=(const std::string &S) {
-+    if (!S.empty())
-+      Value = S;
-+  }
-+
-+  std::string Value;
-+};
-+
-+struct GenericFilenameLocations {
-+  GenericFilenameLocations() : Value() { }
-+  GenericFilenameLocations(const std::string &S)
-+  : Value() {
-+    Value.push_back(S);
-+  }
-+
-+  void operator=(const std::string &S) {
-+    if (!S.empty())
-+      Value.push_back(S);
-+  }
-+
-+  std::vector<std::string> Value;
-+};
-+
-+//===----------------------------------------------------------------------===//
- // Option Category class
- //
- class OptionCategory {
-@@ -162,9 +195,15 @@
- // Option Base class
- //
- class alias;
-+
- class Option {
-   friend class alias;
- 
-+protected:
-+  /// RegisteredOptionList - This is the list of the command line options
-+  /// that have statically constructed themselves.
-+  static Option *RegisteredOptionList;
-+
-   // handleOccurrences - Overriden by subclasses to handle the value passed into
-   // an argument.  Should return true if there was an error processing the
-   // argument and the program should exit.
-@@ -182,13 +221,13 @@
-   int NumOccurrences; // The number of times specified
-   // Occurrences, HiddenFlag, and Formatting are all enum types but to avoid
-   // problems with signed enums in bitfields.
--  unsigned Occurrences : 3; // enum NumOccurrencesFlag
-+  unsigned Occurrences; // enum NumOccurrencesFlag
-   // not using the enum type for 'Value' because zero is an implementation
-   // detail representing the non-value
--  unsigned Value : 2;
--  unsigned HiddenFlag : 2; // enum OptionHidden
--  unsigned Formatting : 2; // enum FormattingFlags
--  unsigned Misc : 3;
-+  unsigned Value;
-+  unsigned HiddenFlag; // enum OptionHidden
-+  unsigned Formatting; // enum FormattingFlags
-+  unsigned Misc;
-   unsigned Position;       // Position of last occurrence of the option
-   unsigned AdditionalVals; // Greater than 0 for multi-valued option.
-   Option *NextRegistered;  // Singly linked list of registered options.
-@@ -200,23 +239,28 @@
-   OptionCategory *Category; // The Category this option belongs to
- 
-   inline enum NumOccurrencesFlag getNumOccurrencesFlag() const {
--    return (enum NumOccurrencesFlag)Occurrences;
-+    return static_cast<enum NumOccurrencesFlag>(Occurrences);
-   }
-+
-   inline enum ValueExpected getValueExpectedFlag() const {
--    return Value ? ((enum ValueExpected)Value) : getValueExpectedFlagDefault();
-+    return Value ?  static_cast<enum ValueExpected>(Value) :
-+      static_cast<enum ValueExpected>(getValueExpectedFlagDefault());
-   }
-+
-   inline enum OptionHidden getOptionHiddenFlag() const {
--    return (enum OptionHidden)HiddenFlag;
-+    return static_cast<enum OptionHidden>(HiddenFlag);
-   }
-+
-   inline enum FormattingFlags getFormattingFlag() const {
--    return (enum FormattingFlags)Formatting;
-+    return static_cast<enum FormattingFlags>(Formatting);
-   }
-+
-   inline unsigned getMiscFlags() const { return Misc; }
-   inline unsigned getPosition() const { return Position; }
-   inline unsigned getNumAdditionalVals() const { return AdditionalVals; }
- 
-   // hasArgStr - Return true if the argstr != ""
--  bool hasArgStr() const { return ArgStr[0] != 0; }
-+  bool hasArgStr() const { return ArgStr && *ArgStr != '\0'; }
- 
-   //-------------------------------------------------------------------------===
-   // Accessor functions set by OptionModifiers
-@@ -233,16 +277,78 @@
-   void setCategory(OptionCategory &C) { Category = &C; }
- 
- protected:
-+  Option() : NumOccurrences(0), Occurrences(0), Value(0), HiddenFlag(0),
-+  Formatting(0), Misc(0), Position(0), AdditionalVals(0),
-+  NextRegistered(0), ArgStr(""), HelpStr(""), ValueStr(""),
-+  Category(0) { }
-   explicit Option(enum NumOccurrencesFlag OccurrencesFlag,
-                   enum OptionHidden Hidden)
--      : NumOccurrences(0), Occurrences(OccurrencesFlag), Value(0),
--        HiddenFlag(Hidden), Formatting(NormalFormatting), Misc(0), Position(0),
--        AdditionalVals(0), NextRegistered(nullptr), ArgStr(""), HelpStr(""),
--        ValueStr(""), Category(&GeneralCategory) {}
-+    : NumOccurrences(0), Occurrences(OccurrencesFlag), Value(0),
-+    HiddenFlag(Hidden), Formatting(NormalFormatting), Misc(0), Position(0),
-+    AdditionalVals(0), NextRegistered(nullptr), ArgStr(""), HelpStr(""),
-+    ValueStr(""), Category(&GeneralCategory) {}
- 
-   inline void setNumAdditionalVals(unsigned n) { AdditionalVals = n; }
- 
- public:
-+  Option(const Option &RHS)
-+  : NumOccurrences(RHS.NumOccurrences), Occurrences(RHS.Occurrences),
-+  Value(RHS.Value), HiddenFlag(RHS.HiddenFlag),
-+  Formatting(RHS.Formatting), Misc(RHS.Misc),
-+  Position(RHS.Position), AdditionalVals(RHS.AdditionalVals),
-+  NextRegistered(RHS.NextRegistered), ArgStr(RHS.ArgStr),
-+  HelpStr(RHS.HelpStr), ValueStr(RHS.ValueStr),
-+  Category(RHS.Category) { }
-+
-+  Option(Option &&RHS)
-+  : NumOccurrences(RHS.NumOccurrences), Occurrences(RHS.Occurrences),
-+  Value(RHS.Value), HiddenFlag(RHS.HiddenFlag),
-+  Formatting(RHS.Formatting), Misc(RHS.Misc),
-+  Position(RHS.Position), AdditionalVals(RHS.AdditionalVals),
-+  NextRegistered(RHS.NextRegistered), ArgStr(RHS.ArgStr),
-+  HelpStr(RHS.HelpStr), ValueStr(RHS.ValueStr),
-+  Category(RHS.Category) { }
-+
-+  Option &operator=(const Option &RHS) {
-+    if (this != &RHS) {
-+      NumOccurrences = RHS.NumOccurrences;
-+      Occurrences = RHS.Occurrences;
-+      Value = RHS.Value;
-+      HiddenFlag = RHS.HiddenFlag;
-+      Formatting = RHS.Formatting;
-+      Misc = RHS.Misc;
-+      Position = RHS.Position;
-+      AdditionalVals = RHS.AdditionalVals;
-+      NextRegistered = RHS.NextRegistered;
-+      ArgStr = RHS.ArgStr;
-+      HelpStr = RHS.HelpStr;
-+      ValueStr = RHS.ValueStr;
-+      Category = RHS.Category;
-+    }
-+
-+    return *this;
-+  }
-+
-+  const Option &operator=(Option &&RHS) {
-+    if (this != &RHS) {
-+      NumOccurrences = RHS.NumOccurrences;
-+      Occurrences = RHS.Occurrences;
-+      Value = RHS.Value;
-+      HiddenFlag = RHS.HiddenFlag;
-+      Formatting = RHS.Formatting;
-+      Misc = RHS.Misc;
-+      Position = RHS.Position;
-+      AdditionalVals = RHS.AdditionalVals;
-+      NextRegistered = RHS.NextRegistered;
-+      ArgStr = RHS.ArgStr;
-+      HelpStr = RHS.HelpStr;
-+      ValueStr = RHS.ValueStr;
-+      Category = RHS.Category;
-+    }
-+
-+    return *this;
-+  }
-+
-   // addArgument - Register this argument with the commandline system.
-   //
-   void addArgument();
-@@ -253,8 +359,20 @@
-   /// For testing purposes only.
-   void removeArgument();
- 
-+  static void registerOption(Option *O) {
-+    assert(O && "Invalid argument!");
-+
-+    O->NextRegistered = RegisteredOptionList;
-+    RegisteredOptionList = O;
-+    MarkOptionsChanged();
-+  }
-+
-   Option *getNextRegisteredOption() const { return NextRegistered; }
- 
-+  static Option *getRegisteredOptionList() {
-+    return Option::RegisteredOptionList;
-+  }
-+
-   // Return the width of the option tag for printing...
-   virtual size_t getOptionWidth() const = 0;
- 
-@@ -265,7 +383,7 @@
- 
-   virtual void printOptionValue(size_t GlobalWidth, bool Force) const = 0;
- 
--  virtual void getExtraOptionNames(SmallVectorImpl<const char *> &) {}
-+  virtual void getExtraOptionNames(std::vector<const char*> &V) { }
- 
-   // addOccurrence - Wrapper around handleOccurrence that enforces Flags.
-   //
-@@ -277,7 +395,7 @@
- 
- public:
-   inline int getNumOccurrences() const { return NumOccurrences; }
--  virtual ~Option() {}
-+  virtual ~Option() { }
- };
- 
- //===----------------------------------------------------------------------===//
-@@ -304,29 +422,39 @@
- // the default constructor for the argument type does not give you what you
- // want.  This is only valid on "opt" arguments, not on "list" arguments.
- //
--template <class Ty> struct initializer {
-+template <typename Ty> struct initializer {
-   const Ty &Init;
--  initializer(const Ty &Val) : Init(Val) {}
- 
--  template <class Opt> void apply(Opt &O) const { O.setInitialValue(Init); }
-+  initializer(const Ty &Val) : Init(Val) { }
-+  initializer(const initializer &RHS) : Init(RHS.Init) { }
-+  initializer(initializer &&RHS) : Init(RHS.Init) { }
-+
-+  template <typename Opt>
-+  void apply(Opt &O) const { O.setInitialValue(Init); }
- };
- 
--template <class Ty> initializer<Ty> init(const Ty &Val) {
--  return initializer<Ty>(Val);
-+template<typename Ty>
-+initializer<Ty> init(const Ty &Val) {
-+  llvm::cl::initializer<Ty> I(Val);
-+  return I;
- }
- 
- // location - Allow the user to specify which external variable they want to
- // store the results of the command line argument processing into, if they don't
- // want to store it in the option itself.
- //
--template <class Ty> struct LocationClass {
-+template <typename Ty> struct LocationClass {
-   Ty &Loc;
--  LocationClass(Ty &L) : Loc(L) {}
- 
--  template <class Opt> void apply(Opt &O) const { O.setLocation(O, Loc); }
-+  LocationClass(Ty &L) : Loc(L) { }
-+  LocationClass(const LocationClass &RHS) : Loc(RHS.Loc) { }
-+  LocationClass(LocationClass &&RHS) : Loc(RHS.Loc) { }
-+
-+  template<typename Opt>
-+  void apply(Opt &O) const { O.setLocation(O, Loc); }
- };
- 
--template <class Ty> LocationClass<Ty> location(Ty &L) {
-+template <typename Ty> LocationClass<Ty> location(Ty &L) {
-   return LocationClass<Ty>(L);
- }
- 
-@@ -334,17 +462,22 @@
- // to.
- struct cat {
-   OptionCategory &Category;
--  cat(OptionCategory &c) : Category(c) {}
- 
--  template <class Opt> void apply(Opt &O) const { O.setCategory(Category); }
-+  cat(OptionCategory &c) : Category(c) { }
-+  cat(const cat &RHS) : Category(RHS.Category) { }
-+  virtual ~cat() { }
-+
-+  template <typename Opt>
-+  void apply(Opt &O) const { O.setCategory(Category); }
- };
- 
- //===----------------------------------------------------------------------===//
- // OptionValue class
- 
- // Support value comparison outside the template.
--struct GenericOptionValue {
--  virtual ~GenericOptionValue() {}
-+class GenericOptionValue {
-+public:
-+  virtual ~GenericOptionValue() { }
-   virtual bool compare(const GenericOptionValue &V) const = 0;
- 
- private:
-@@ -458,57 +591,6 @@
- };
- 
- //===----------------------------------------------------------------------===//
--// Enum valued command line option
--//
--#define clEnumVal(ENUMVAL, DESC) #ENUMVAL, int(ENUMVAL), DESC
--#define clEnumValN(ENUMVAL, FLAGNAME, DESC) FLAGNAME, int(ENUMVAL), DESC
--#define clEnumValEnd (reinterpret_cast<void *>(0))
--
--// values - For custom data types, allow specifying a group of values together
--// as the values that go into the mapping that the option handler uses.  Note
--// that the values list must always have a 0 at the end of the list to indicate
--// that the list has ended.
--//
--template <class DataType> class ValuesClass {
--  // Use a vector instead of a map, because the lists should be short,
--  // the overhead is less, and most importantly, it keeps them in the order
--  // inserted so we can print our option out nicely.
--  SmallVector<std::pair<const char *, std::pair<int, const char *>>, 4> Values;
--  void processValues(va_list Vals);
--
--public:
--  ValuesClass(const char *EnumName, DataType Val, const char *Desc,
--              va_list ValueArgs) {
--    // Insert the first value, which is required.
--    Values.push_back(std::make_pair(EnumName, std::make_pair(Val, Desc)));
--
--    // Process the varargs portion of the values...
--    while (const char *enumName = va_arg(ValueArgs, const char *)) {
--      DataType EnumVal = static_cast<DataType>(va_arg(ValueArgs, int));
--      const char *EnumDesc = va_arg(ValueArgs, const char *);
--      Values.push_back(std::make_pair(enumName, // Add value to value map
--                                      std::make_pair(EnumVal, EnumDesc)));
--    }
--  }
--
--  template <class Opt> void apply(Opt &O) const {
--    for (size_t i = 0, e = Values.size(); i != e; ++i)
--      O.getParser().addLiteralOption(Values[i].first, Values[i].second.first,
--                                     Values[i].second.second);
--  }
--};
--
--template <class DataType>
--ValuesClass<DataType> LLVM_END_WITH_NULL
--values(const char *Arg, DataType Val, const char *Desc, ...) {
--  va_list ValueArgs;
--  va_start(ValueArgs, Desc);
--  ValuesClass<DataType> Vals(Arg, Val, Desc, ValueArgs);
--  va_end(ValueArgs);
--  return Vals;
--}
--
--//===----------------------------------------------------------------------===//
- // parser class - Parameterizable parser for different data types.  By default,
- // known data types (string, int, bool) have specialized parsers, that do what
- // you would expect.  The default parser, used for data types that are not
-@@ -519,18 +601,23 @@
- // generic_parser_base - This class holds all the non-generic code that we do
- // not need replicated for every instance of the generic parser.  This also
- // allows us to put stuff into CommandLine.cpp
-+// Moved here for an obvious reason.
- //
- class generic_parser_base {
- protected:
-   class GenericOptionInfo {
-   public:
-     GenericOptionInfo(const char *name, const char *helpStr)
--        : Name(name), HelpStr(helpStr) {}
-+      : Name(name), HelpStr(helpStr) {}
-+    virtual ~GenericOptionInfo() { }
-+
-     const char *Name;
-     const char *HelpStr;
-   };
- 
- public:
-+  generic_parser_base() : hasArgStr(false) { }
-+
-   virtual ~generic_parser_base() {} // Base class should have virtual-dtor
- 
-   // getNumOptions - Virtual function implemented by generic subclass to
-@@ -576,7 +663,7 @@
-     hasArgStr = O.hasArgStr();
-   }
- 
--  void getExtraOptionNames(SmallVectorImpl<const char *> &OptionNames) {
-+  void getExtraOptionNames(std::vector<const char *> &OptionNames) {
-     // If there has been no argstr specified, that means that we need to add an
-     // argument for every possible option.  This ensures that our options are
-     // vectored to us.
-@@ -612,34 +699,48 @@
-   bool hasArgStr;
- };
- 
-+
- // Default parser implementation - This implementation depends on having a
- // mapping of recognized options to values of some sort.  In addition to this,
- // each entry in the mapping also tracks a help message that is printed with the
- // command line option for -help.  Because this is a simple mapping parser, the
- // data type can be any unsupported type.
- //
--template <class DataType> class parser : public generic_parser_base {
-+template <typename DataType>
-+class parser : public generic_parser_base {
- protected:
-   class OptionInfo : public GenericOptionInfo {
-   public:
--    OptionInfo(const char *name, DataType v, const char *helpStr)
--        : GenericOptionInfo(name, helpStr), V(v) {}
-+    OptionInfo(const char *Name, DataType DT, const char *helpStr)
-+      : GenericOptionInfo(Name, helpStr), V(DT) {}
-+    ~OptionInfo() { }
-+
-     OptionValue<DataType> V;
-   };
--  SmallVector<OptionInfo, 8> Values;
-+
-+  std::vector<OptionInfo> Values;
- 
- public:
-   typedef DataType parser_data_type;
- 
-+  parser<DataType>() : generic_parser_base(), Values() { }
-+  virtual ~parser<DataType>() { }
-+
-   // Implement virtual functions needed by generic_parser_base
--  unsigned getNumOptions() const override { return unsigned(Values.size()); }
--  const char *getOption(unsigned N) const override { return Values[N].Name; }
--  const char *getDescription(unsigned N) const override {
-+  virtual unsigned getNumOptions() const override {
-+    return static_cast<unsigned>(Values.size());
-+  }
-+
-+  virtual const char *getOption(unsigned N) const override {
-+    return Values[N].Name;
-+  }
-+
-+  virtual const char *getDescription(unsigned N) const override {
-     return Values[N].HelpStr;
-   }
- 
-   // getOptionValue - Return the value of option name N.
--  const GenericOptionValue &getOptionValue(unsigned N) const override {
-+  virtual const GenericOptionValue &getOptionValue(unsigned N) const override {
-     return Values[N].V;
-   }
- 
-@@ -662,7 +763,7 @@
- 
-   /// addLiteralOption - Add an entry to the mapping table.
-   ///
--  template <class DT>
-+  template<typename DT>
-   void addLiteralOption(const char *Name, const DT &V, const char *HelpStr) {
-     assert(findOption(Name) == Values.size() && "Option already exists!");
-     OptionInfo X(Name, static_cast<DataType>(V), HelpStr);
-@@ -670,6 +771,14 @@
-     MarkOptionsChanged();
-   }
- 
-+  void addLiteralOption(const char *Name, const DataType &V,
-+                        const char *HelpStr) {
-+    assert(findOption(Name) == Values.size() && "Option already exists!");
-+    OptionInfo X(Name, V, HelpStr);
-+    Values.push_back(X);
-+    MarkOptionsChanged();
-+  }
-+
-   /// removeLiteralOption - Remove the specified option.
-   ///
-   void removeLiteralOption(const char *Name) {
-@@ -679,18 +788,95 @@
-   }
- };
- 
-+//===----------------------------------------------------------------------===//
-+// Enum valued command line option
-+//
-+#define clEnumVal(ENUMVAL, DESC) #ENUMVAL, int(ENUMVAL), DESC
-+#define clEnumValN(ENUMVAL, FLAGNAME, DESC) FLAGNAME, int(ENUMVAL), DESC
-+#define clEnumValEnd (reinterpret_cast<void *>(0))
-+
-+// values - For custom data types, allow specifying a group of values together
-+// as the values that go into the mapping that the option handler uses.  Note
-+// that the values list must always have a 0 at the end of the list to indicate
-+// that the list has ended.
-+//
-+template <typename DataType>
-+class ValuesClass {
-+  // Use a vector instead of a map, because the lists should be short,
-+  // the overhead is less, and most importantly, it keeps them in the order
-+  // inserted so we can print our option out nicely.
-+  std::vector<std::pair<const char*, std::pair<int, const char*> > > Values;
-+  void processValues(va_list Vals);
-+
-+public:
-+  ValuesClass(const char *EnumName, DataType Val, const char *Desc,
-+              va_list ValueArgs) : Values() {
-+    // Insert the first value, which is required.
-+    Values.push_back(std::make_pair(EnumName, std::make_pair(Val, Desc)));
-+
-+    // Process the varargs portion of the values...
-+    while (const char *enumName = va_arg(ValueArgs, const char *)) {
-+      DataType EnumVal = static_cast<DataType>(va_arg(ValueArgs, int));
-+      const char *EnumDesc = va_arg(ValueArgs, const char *);
-+
-+      Values.push_back(std::make_pair(enumName, // Add value to value map
-+                                      std::make_pair(EnumVal, EnumDesc)));
-+    }
-+  }
-+
-+  ValuesClass(const ValuesClass &RHS)
-+  : Values(RHS.Values) { }
-+
-+  ValuesClass(ValuesClass &&RHS)
-+  : Values(RHS.Values) { }
-+
-+  ValuesClass &operator=(const ValuesClass &RHS) {
-+    if (this != &RHS)
-+      Values.operator=(RHS.Values);
-+
-+    return *this;
-+  }
-+
-+  ValuesClass &operator=(ValuesClass &&RHS) {
-+    if (this != &RHS)
-+      Values.operator=(RHS.Values);
-+
-+    return *this;
-+  }
-+
-+  ~ValuesClass() { }
-+
-+  template <typename Opt> void apply(Opt &O) const {
-+    for (size_t i = 0, e = Values.size(); i != e; ++i) {
-+      O.getParser().addLiteralOption(Values[i].first, Values[i].second.first,
-+                                     Values[i].second.second);
-+    }
-+  }
-+};
-+
-+template <class DataType>
-+ValuesClass<DataType> LLVM_END_WITH_NULL
-+values(const char *Arg, DataType Val, const char *Desc, ...) {
-+  va_list ValueArgs;
-+  va_start(ValueArgs, Desc);
-+  ValuesClass<DataType> Vals(Arg, Val, Desc, ValueArgs);
-+  va_end(ValueArgs);
-+  return Vals;
-+}
-+
- //--------------------------------------------------
- // basic_parser - Super class of parsers to provide boilerplate code
- //
- class basic_parser_impl { // non-template implementation of basic_parser<t>
- public:
-+  basic_parser_impl() { }
-   virtual ~basic_parser_impl() {}
- 
-   enum ValueExpected getValueExpectedFlagDefault() const {
-     return ValueRequired;
-   }
- 
--  void getExtraOptionNames(SmallVectorImpl<const char *> &) {}
-+  void getExtraOptionNames(std::vector<const char *> &V) { }
- 
-   void initialize(Option &) {}
- 
-@@ -720,10 +906,46 @@
- // basic_parser - The real basic parser is just a template wrapper that provides
- // a typedef for the provided data type.
- //
--template <class DataType> class basic_parser : public basic_parser_impl {
-+template <typename DataType>
-+class basic_parser : public basic_parser_impl {
- public:
-+  basic_parser<DataType>() : basic_parser_impl(), Values() { }
-+  ~basic_parser<DataType>() { }
-+
-+  unsigned getNumOptions() const {
-+    return static_cast<unsigned>(Values.size());
-+  }
-+
-+  const char *getOption(unsigned I) {
-+    assert(I < static_cast<unsigned>(Values.size()) &&
-+           "Index is out-of-range!");
-+    return Values[I].Name;
-+  }
-+
-+  const char *getDescription(unsigned I) {
-+    assert(I < static_cast<unsigned>(Values.size()) &&
-+           "Index is out-of-range!");
-+    return Values[I].Help;
-+  }
-+
-   typedef DataType parser_data_type;
-   typedef OptionValue<DataType> OptVal;
-+
-+protected:
-+  template<typename SameDataType>
-+  class OptionInfo {
-+  public:
-+    OptionInfo(const char *NameStr, SameDataType DT, const char *HelpStr)
-+    : Name(NameStr), Help(HelpStr), V(DT) { }
-+
-+    ~OptionInfo() { }
-+
-+    const char *Name;
-+    const char *Help;
-+    OptionValue<SameDataType> V;
-+  };
-+
-+  std::vector<OptionInfo<DataType> > Values;
- };
- 
- //--------------------------------------------------
-@@ -733,6 +955,9 @@
-   const char *ArgStr;
- 
- public:
-+  parser<bool>() : basic_parser<bool>() { }
-+  virtual ~parser<bool>() { }
-+
-   // parse - Return true on error.
-   bool parse(Option &O, StringRef ArgName, StringRef Arg, bool &Val);
- 
-@@ -745,11 +970,17 @@
-   // getValueName - Do not print =<value> at all.
-   const char *getValueName() const override { return nullptr; }
- 
-+  void addLiteralOption(const char *Name, bool V, const char *HelpStr) {
-+    OptionInfo<bool> OI(Name, V, HelpStr);
-+    Values.push_back(OI);
-+    MarkOptionsChanged();
-+  }
-+
-   void printOptionDiff(const Option &O, bool V, OptVal Default,
-                        size_t GlobalWidth) const;
- 
-   // An out-of-line virtual method to provide a 'home' for this class.
--  void anchor() override;
-+  virtual void anchor() override;
- };
- 
- EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<bool>);
-@@ -758,6 +989,9 @@
- // parser<boolOrDefault>
- template <> class parser<boolOrDefault> : public basic_parser<boolOrDefault> {
- public:
-+  parser<boolOrDefault>() : basic_parser<boolOrDefault>() { }
-+  virtual ~parser<boolOrDefault>() { }
-+
-   // parse - Return true on error.
-   bool parse(Option &O, StringRef ArgName, StringRef Arg, boolOrDefault &Val);
- 
-@@ -772,7 +1006,7 @@
-                        size_t GlobalWidth) const;
- 
-   // An out-of-line virtual method to provide a 'home' for this class.
--  void anchor() override;
-+  virtual void anchor() override;
- };
- 
- EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
-@@ -782,12 +1016,21 @@
- //
- template <> class parser<int> : public basic_parser<int> {
- public:
-+  parser<int>() : basic_parser<int>() { }
-+  virtual ~parser<int>() { }
-+
-   // parse - Return true on error.
-   bool parse(Option &O, StringRef ArgName, StringRef Arg, int &Val);
- 
-   // getValueName - Overload in subclass to provide a better default value.
-   const char *getValueName() const override { return "int"; }
- 
-+  void addLiteralOption(const char *Name, int V, const char *HelpStr) {
-+    OptionInfo<int> OI(Name, V, HelpStr);
-+    Values.push_back(OI);
-+    MarkOptionsChanged();
-+  }
-+
-   void printOptionDiff(const Option &O, int V, OptVal Default,
-                        size_t GlobalWidth) const;
- 
-@@ -802,12 +1045,21 @@
- //
- template <> class parser<unsigned> : public basic_parser<unsigned> {
- public:
-+  parser<unsigned>() : basic_parser<unsigned>() { }
-+  virtual ~parser<unsigned>() { }
-+
-   // parse - Return true on error.
-   bool parse(Option &O, StringRef ArgName, StringRef Arg, unsigned &Val);
- 
-   // getValueName - Overload in subclass to provide a better default value.
-   const char *getValueName() const override { return "uint"; }
- 
-+  void addLiteralOption(const char *Name, unsigned V, const char *HelpStr) {
-+    OptionInfo<unsigned> OI(Name, V, HelpStr);
-+    Values.push_back(OI);
-+    MarkOptionsChanged();
-+  }
-+
-   void printOptionDiff(const Option &O, unsigned V, OptVal Default,
-                        size_t GlobalWidth) const;
- 
-@@ -823,6 +1075,9 @@
- template <>
- class parser<unsigned long long> : public basic_parser<unsigned long long> {
- public:
-+  parser<unsigned long long>() : basic_parser<unsigned long long>() { }
-+  virtual ~parser<unsigned long long>() { }
-+
-   // parse - Return true on error.
-   bool parse(Option &O, StringRef ArgName, StringRef Arg,
-              unsigned long long &Val);
-@@ -844,6 +1099,9 @@
- //
- template <> class parser<double> : public basic_parser<double> {
- public:
-+  parser<double>() : basic_parser<double>() { }
-+  virtual ~parser<double>() { }
-+
-   // parse - Return true on error.
-   bool parse(Option &O, StringRef ArgName, StringRef Arg, double &Val);
- 
-@@ -864,6 +1122,9 @@
- //
- template <> class parser<float> : public basic_parser<float> {
- public:
-+  parser<float>() : basic_parser<float>() { }
-+  virtual ~parser<float>() { }
-+
-   // parse - Return true on error.
-   bool parse(Option &O, StringRef ArgName, StringRef Arg, float &Val);
- 
-@@ -884,6 +1145,9 @@
- //
- template <> class parser<std::string> : public basic_parser<std::string> {
- public:
-+  parser<std::string>() : basic_parser<std::string>() { }
-+  virtual ~parser<std::string>() { }
-+
-   // parse - Return true on error.
-   bool parse(Option &, StringRef, StringRef Arg, std::string &Value) {
-     Value = Arg.str();
-@@ -893,7 +1157,13 @@
-   // getValueName - Overload in subclass to provide a better default value.
-   const char *getValueName() const override { return "string"; }
- 
--  void printOptionDiff(const Option &O, StringRef V, OptVal Default,
-+  void addLiteralOption(const char *Name, int V, const char *HelpStr) {
-+    OptionInfo<std::string> OI(Name, std::to_string(V), HelpStr);
-+    Values.push_back(OI);
-+    MarkOptionsChanged();
-+  }
-+
-+  void printOptionDiff(const Option &O, const std::string &V, OptVal Default,
-                        size_t GlobalWidth) const;
- 
-   // An out-of-line virtual method to provide a 'home' for this class.
-@@ -907,6 +1177,9 @@
- //
- template <> class parser<char> : public basic_parser<char> {
- public:
-+  parser<char>() : basic_parser<char>() { }
-+  virtual ~parser<char>() { }
-+
-   // parse - Return true on error.
-   bool parse(Option &, StringRef, StringRef Arg, char &Value) {
-     Value = Arg[0];
-@@ -916,6 +1189,12 @@
-   // getValueName - Overload in subclass to provide a better default value.
-   const char *getValueName() const override { return "char"; }
- 
-+  void addLiteralOption(const char *Name, char V, const char *HelpStr) {
-+    OptionInfo<char> OI(Name, V, HelpStr);
-+    Values.push_back(OI);
-+    MarkOptionsChanged();
-+  }
-+
-   void printOptionDiff(const Option &O, char V, OptVal Default,
-                        size_t GlobalWidth) const;
- 
-@@ -976,8 +1255,9 @@
- // not correctly respond to the apply method).  Because the syntax to use this
- // is a pain, we have the 'apply' method below to handle the nastiness...
- //
--template <class Mod> struct applicator {
--  template <class Opt> static void opt(const Mod &M, Opt &O) { M.apply(O); }
-+template <typename Mod> struct applicator {
-+  template <typename Opt>
-+  static void opt(const Mod &M, Opt &O) { M.apply(O); }
- };
- 
- // Handle const char* as a special case...
-@@ -1039,11 +1319,16 @@
-   }
- 
- public:
--  opt_storage() : Location(nullptr) {}
-+  opt_storage() : Location(nullptr), Default() { }
-+  opt_storage(const opt_storage &RHS)
-+  : Location(RHS.Location), Default(RHS.Default) { }
-+  opt_storage(opt_storage &&RHS)
-+  : Location(RHS.Location), Default(RHS.Default) { }
- 
-   bool setLocation(Option &O, DataType &L) {
-     if (Location)
-       return O.error("cl::location(x) specified more than once!");
-+
-     Location = &L;
-     Default = L;
-     return false;
-@@ -1077,8 +1362,47 @@
- template <class DataType>
- class opt_storage<DataType, false, true> : public DataType {
- public:
-+  opt_storage() : DataType(), Location(nullptr), Default() { }
-+  opt_storage(const opt_storage &RHS)
-+  : DataType(RHS), Location(RHS.Location), Default(RHS.Default) { }
-+  opt_storage(opt_storage &&RHS)
-+  : DataType(RHS), Location(RHS.Location), Default(RHS.Default) { }
-+
-+  opt_storage<DataType, false, true>
-+  &operator=(const opt_storage<DataType, false, true> &RHS) {
-+    if (this != &RHS) {
-+      DataType::operator=(RHS);
-+      Location = RHS.Location;
-+      Default = RHS.Default;
-+    }
-+
-+    return *this;
-+  }
-+
-+  opt_storage<DataType, false, true>
-+  &operator=(opt_storage<DataType, false, true> &&RHS) {
-+    if (this != &RHS) {
-+      DataType::operator=(RHS);
-+      Location = RHS.Location;
-+      Default = RHS.Default;
-+    }
-+
-+    return *this;
-+  }
-+
-+
-+  DataType *Location;
-   OptionValue<DataType> Default;
- 
-+  bool setLocation(Option &O, DataType &L) {
-+    if (Location)
-+      return O.error("cl::location(x) specified more than once!");
-+
-+    Location = &L;
-+    Default = L;
-+    return false;
-+  }
-+
-   template <class T> void setValue(const T &V, bool initial = false) {
-     DataType::operator=(V);
-     if (initial)
-@@ -1102,13 +1426,45 @@
- 
-   // Make sure we initialize the value with the default constructor for the
-   // type.
--  opt_storage() : Value(DataType()), Default(DataType()) {}
-+  opt_storage() : Value(DataType()), Default(DataType()) { }
-+  opt_storage(const opt_storage &RHS)
-+  : Value(RHS.Value), Default(RHS.Default) { }
-+  opt_storage(opt_storage &&RHS)
-+  : Value(RHS.Location), Default(RHS.Default) { }
-+
-+  opt_storage<DataType, false, false>
-+  &operator=(const opt_storage<DataType, false, false> &RHS) {
-+    if (this != &RHS) {
-+      Value = RHS.Value;
-+      Default = RHS.Default;
-+    }
-+
-+    return *this;
-+  }
-+
-+  opt_storage<DataType, false, false>
-+  &operator=(opt_storage<DataType, false, false> &&RHS) {
-+    if (this != &RHS) {
-+      Value = RHS.Value;
-+      Default = RHS.Default;
-+    }
-+
-+    return *this;
-+  }
-+
-+
-+  bool setLocation(Option &O, DataType &L) {
-+    Value = L;
-+    Default = Value;
-+    return false;
-+  }
- 
-   template <class T> void setValue(const T &V, bool initial = false) {
-     Value = V;
-     if (initial)
-       Default = V;
-   }
-+
-   DataType &getValue() { return Value; }
-   DataType getValue() const { return Value; }
- 
-@@ -1123,19 +1479,21 @@
- //===----------------------------------------------------------------------===//
- // opt - A scalar command line option.
- //
--template <class DataType, bool ExternalStorage = false,
--          class ParserClass = parser<DataType>>
-+template <typename DataType, bool ExternalStorage = false,
-+          typename ParserClass = parser<DataType> >
- class opt : public Option,
-             public opt_storage<DataType, ExternalStorage,
-                                std::is_class<DataType>::value> {
-   ParserClass Parser;
- 
--  bool handleOccurrence(unsigned pos, StringRef ArgName,
--                        StringRef Arg) override {
-+protected:
-+  virtual bool handleOccurrence(unsigned pos, StringRef ArgName,
-+                                StringRef Arg) override {
-     typename ParserClass::parser_data_type Val =
-         typename ParserClass::parser_data_type();
-     if (Parser.parse(*this, ArgName, Arg, Val))
-       return true; // Parse error!
-+
-     this->setValue(Val);
-     this->setPosition(pos);
-     return false;
-@@ -1145,7 +1503,7 @@
-     return Parser.getValueExpectedFlagDefault();
-   }
-   void
--  getExtraOptionNames(SmallVectorImpl<const char *> &OptionNames) override {
-+  getExtraOptionNames(std::vector<const char *> &OptionNames) override {
-     return Parser.getExtraOptionNames(OptionNames);
-   }
- 
-@@ -1170,11 +1528,33 @@
-   }
- 
- public:
-+  opt() : Option(), opt_storage<DataType, ExternalStorage,
-+                                std::is_class<DataType>::value>(),
-+          Parser() { }
-+
-+  opt(const opt &RHS) : Option(RHS),
-+  opt_storage<DataType, ExternalStorage,
-+              std::is_class<DataType>::value>(RHS),
-+  Parser(RHS.Parser) { }
-+
-+  ~opt() { }
-+
-   // setInitialValue - Used by the cl::init modifier...
-   void setInitialValue(const DataType &V) { this->setValue(V, true); }
- 
-   ParserClass &getParser() { return Parser; }
- 
-+  bool setLocation(Option &O, DataType &L) {
-+    bool R = opt_storage<DataType, ExternalStorage,
-+                         std::is_class<DataType>::value>::setLocation(O, L);
-+    return R;
-+  }
-+
-+  void addArgument() {
-+    assert(!NextRegistered && "argument multiply registered!");
-+    Option::registerOption(this);
-+  }
-+
-   template <class T> DataType &operator=(const T &Val) {
-     this->setValue(Val);
-     return this->getValue();
-@@ -1271,6 +1651,23 @@
-     apply(M7, this);
-     done();
-   }
-+  // Nine options...
-+  template <class M0t, class M1t, class M2t, class M3t, class M4t, class M5t,
-+            class M6t, class M7t, class M8t>
-+  opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3, const M4t &M4,
-+      const M5t &M5, const M6t &M6, const M7t &M7, const M8t &M8)
-+      : Option(Optional, NotHidden) {
-+    apply(M0, this);
-+    apply(M1, this);
-+    apply(M2, this);
-+    apply(M3, this);
-+    apply(M4, this);
-+    apply(M5, this);
-+    apply(M6, this);
-+    apply(M7, this);
-+    apply(M8, this);
-+    done();
-+  }
- };
- 
- EXTERN_TEMPLATE_INSTANTIATION(class opt<unsigned>);
-@@ -1291,10 +1688,12 @@
- 
- public:
-   list_storage() : Location(0) {}
-+  virtual ~list_storage() { }
- 
-   bool setLocation(Option &O, StorageClass &L) {
-     if (Location)
-       return O.error("cl::location(x) specified more than once!");
-+
-     Location = &L;
-     return false;
-   }
-@@ -1312,9 +1711,38 @@
- //
- template <class DataType>
- class list_storage<DataType, bool> : public std::vector<DataType> {
-+private:
-+  list_storage<DataType, bool>(list_storage<DataType, bool> &&RHS) LLVM_DELETED_FUNCTION;
-+  list_storage<DataType, bool>
-+  &&operator=(list_storage<DataType, bool> &&RHS) LLVM_DELETED_FUNCTION;
-+
- public:
-+  list_storage<DataType, bool>() : std::vector<DataType>() { }
-+  list_storage<DataType, bool>(const list_storage<DataType, bool> &RHS)
-+    : std::vector<DataType>(RHS) { }
-+  list_storage<DataType, bool>
-+  &operator=(const list_storage<DataType, bool> &RHS) {
-+    if (this != &RHS)
-+      std::vector<DataType>::operator=(RHS);
-+
-+    return *this;
-+  }
-+
-+  virtual ~list_storage<DataType, bool>() { }
-+
-   template <class T> void addValue(const T &V) {
--    std::vector<DataType>::push_back(V);
-+    T LV(V);
-+    this->push_back(LV);
-+  }
-+
-+  void addValue(const DataType &V) {
-+    DataType LV(V);
-+    std::vector<DataType> &VEC = static_cast<std::vector<DataType>& >(*this);
-+    VEC.push_back(LV);
-+  }
-+
-+  const std::vector<DataType> &getStorage() const {
-+    return static_cast<const std::vector<DataType>& >(*this);
-   }
- };
- 
-@@ -1324,40 +1752,47 @@
- template <class DataType, class Storage = bool,
-           class ParserClass = parser<DataType>>
- class list : public Option, public list_storage<DataType, Storage> {
-+  friend class Option;
-+
-   std::vector<unsigned> Positions;
-   ParserClass Parser;
- 
--  enum ValueExpected getValueExpectedFlagDefault() const override {
-+protected:
-+  virtual enum ValueExpected getValueExpectedFlagDefault() const override {
-     return Parser.getValueExpectedFlagDefault();
-   }
--  void
--  getExtraOptionNames(SmallVectorImpl<const char *> &OptionNames) override {
-+
-+  virtual void
-+  getExtraOptionNames(std::vector<const char *> &OptionNames) override {
-     return Parser.getExtraOptionNames(OptionNames);
-   }
- 
--  bool handleOccurrence(unsigned pos, StringRef ArgName,
--                        StringRef Arg) override {
-+  virtual bool handleOccurrence(unsigned pos, StringRef ArgName,
-+                                StringRef Arg) override {
-     typename ParserClass::parser_data_type Val =
-         typename ParserClass::parser_data_type();
-+
-     if (Parser.parse(*this, ArgName, Arg, Val))
-       return true; // Parse Error!
--    list_storage<DataType, Storage>::addValue(Val);
-+
-+    this->addValue(Val);
-     setPosition(pos);
-     Positions.push_back(pos);
-     return false;
-   }
- 
-   // Forward printing stuff to the parser...
--  size_t getOptionWidth() const override {
-+  virtual size_t getOptionWidth() const override {
-     return Parser.getOptionWidth(*this);
-   }
--  void printOptionInfo(size_t GlobalWidth) const override {
-+
-+  virtual void printOptionInfo(size_t GlobalWidth) const override {
-     Parser.printOptionInfo(*this, GlobalWidth);
-   }
- 
-   // Unimplemented: list options don't currently store their default value.
--  void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override {
--  }
-+  virtual void
-+  printOptionValue(size_t GlobalWidth, bool Force) const override { }
- 
-   void done() {
-     addArgument();
-@@ -1365,8 +1800,26 @@
-   }
- 
- public:
-+  list() : Option(), list_storage<DataType, Storage>(),
-+  Positions(), Parser(ParserClass()) { }
-+
-+  list(const Option &O)
-+  : Option(O), list_storage<DataType, Storage>(),
-+  Positions(), Parser(ParserClass()) { }
-+
-+  list(Option *O)
-+  : Option(*O), list_storage<DataType, Storage>(),
-+  Positions(), Parser(ParserClass()) { }
-+
-+  ~list() { }
-+
-   ParserClass &getParser() { return Parser; }
- 
-+  void addArgument() {
-+    assert(!NextRegistered && "argument multiply registered!");
-+    Option::registerOption(this);
-+  }
-+
-   unsigned getPosition(unsigned optnum) const {
-     assert(optnum < this->size() && "Invalid option index");
-     return Positions[optnum];
-@@ -1500,6 +1953,7 @@
-   bool setLocation(Option &O, unsigned &L) {
-     if (Location)
-       return O.error("cl::location(x) specified more than once!");
-+
-     Location = &L;
-     return false;
-   }
-@@ -1551,12 +2005,12 @@
-     return Parser.getValueExpectedFlagDefault();
-   }
-   void
--  getExtraOptionNames(SmallVectorImpl<const char *> &OptionNames) override {
-+  getExtraOptionNames(std::vector<const char *> &OptionNames) override {
-     return Parser.getExtraOptionNames(OptionNames);
-   }
- 
--  bool handleOccurrence(unsigned pos, StringRef ArgName,
--                        StringRef Arg) override {
-+  virtual bool handleOccurrence(unsigned pos, StringRef ArgName,
-+                                StringRef Arg) override {
-     typename ParserClass::parser_data_type Val =
-         typename ParserClass::parser_data_type();
-     if (Parser.parse(*this, ArgName, Arg, Val))
-@@ -1690,14 +2144,17 @@
- 
- class alias : public Option {
-   Option *AliasFor;
--  bool handleOccurrence(unsigned pos, StringRef /*ArgName*/,
--                        StringRef Arg) override {
-+  virtual bool handleOccurrence(unsigned pos, StringRef ArgName,
-+                                StringRef Arg) override {
-+
-     return AliasFor->handleOccurrence(pos, AliasFor->ArgStr, Arg);
-   }
--  bool addOccurrence(unsigned pos, StringRef /*ArgName*/, StringRef Value,
--                     bool MultiArg = false) override {
-+
-+  virtual bool addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
-+                             bool MultiArg = false) override {
-     return AliasFor->addOccurrence(pos, AliasFor->ArgStr, Value, MultiArg);
-   }
-+
-   // Handle printing stuff...
-   size_t getOptionWidth() const override;
-   void printOptionInfo(size_t GlobalWidth) const override;
-@@ -1847,7 +2304,7 @@
- /// lines and end of the response file to be marked with a nullptr string.
- /// \param [out] NewArgv All parsed strings are appended to NewArgv.
- void TokenizeGNUCommandLine(StringRef Source, StringSaver &Saver,
--                            SmallVectorImpl<const char *> &NewArgv,
-+                            std::vector<const char *> &NewArgv,
-                             bool MarkEOLs = false);
- 
- /// \brief Tokenizes a Windows command line which may contain quotes and escaped
-@@ -1862,13 +2319,13 @@
- /// lines and end of the response file to be marked with a nullptr string.
- /// \param [out] NewArgv All parsed strings are appended to NewArgv.
- void TokenizeWindowsCommandLine(StringRef Source, StringSaver &Saver,
--                                SmallVectorImpl<const char *> &NewArgv,
-+                                std::vector<const char *> &NewArgv,
-                                 bool MarkEOLs = false);
- 
- /// \brief String tokenization function type.  Should be compatible with either
- /// Windows or Unix command line tokenizers.
- typedef void (*TokenizerCallback)(StringRef Source, StringSaver &Saver,
--                                  SmallVectorImpl<const char *> &NewArgv,
-+                                  std::vector<const char *> &NewArgv,
-                                   bool MarkEOLs);
- 
- /// \brief Expand response files on a command line recursively using the given
-@@ -1886,7 +2343,7 @@
- /// with nullptrs in the Argv vector.
- /// \return true if all @files were expanded successfully or there were none.
- bool ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
--                         SmallVectorImpl<const char *> &Argv,
-+                         std::vector<const char *> &Argv,
-                          bool MarkEOLs = false);
- 
- } // End namespace cl
---- include/llvm/Support/FileSystem.h	2014-12-15 19:10:29.000000000 -0800
-+++ include/llvm/Support/FileSystem.h	2016-01-24 21:14:49.000000000 -0800
-@@ -680,10 +680,35 @@
- 
- public:
-   explicit directory_entry(const Twine &path, file_status st = file_status())
--    : Path(path.str())
--    , Status(st) {}
-+    : Path(path.str()), Status(st) { }
- 
--  directory_entry() {}
-+  directory_entry() : Path(""), Status(file_status()) { }
-+
-+  directory_entry(const directory_entry &rhs)
-+  : Path(rhs.Path), Status(rhs.Status) { }
-+
-+  directory_entry(directory_entry &&rhs)
-+  : Path(rhs.Path), Status(rhs.Status) { }
-+
-+  ~directory_entry() { }
-+
-+  directory_entry &operator=(const directory_entry &rhs) {
-+    if (this != &rhs) {
-+      Path = rhs.Path;
-+      Status = rhs.Status;
-+    }
-+
-+    return *this;
-+  }
-+
-+  directory_entry &operator=(directory_entry &&rhs) {
-+    if (this != &rhs) {
-+      Path = rhs.Path;
-+      Status = rhs.Status;
-+    }
-+
-+    return *this;
-+  }
- 
-   void assign(const Twine &path, file_status st = file_status()) {
-     Path = path.str();
---- include/llvm/Support/PluginLoader.h	2007-12-29 11:59:42.000000000 -0800
-+++ include/llvm/Support/PluginLoader.h	2016-01-24 11:01:53.000000000 -0800
-@@ -22,6 +22,8 @@
- namespace llvm {
-   struct PluginLoader {
-     void operator=(const std::string &Filename);
-+    bool operator==(const std::string &Filename) const;
-+    bool operator!=(const std::string &Filename) const;
-     static unsigned getNumPlugins();
-     static std::string& getPlugin(unsigned num);
-   };
---- utils/TableGen/AsmMatcherEmitter.cpp	2015-01-03 00:16:29.000000000 -0800
-+++ utils/TableGen/AsmMatcherEmitter.cpp	2016-01-26 14:57:52.000000000 -0800
-@@ -121,7 +121,7 @@
- #define DEBUG_TYPE "asm-matcher-emitter"
- 
- static cl::opt<std::string>
--MatchPrefix("match-prefix", cl::init(""),
-+MatchPrefix("match-prefix", cl::init(std::string("")),
-             cl::desc("Only match instructions with the given prefix"));
- 
- namespace {
---- tools/llc/llc.cpp	2014-12-11 23:52:06.000000000 -0800
-+++ tools/llc/llc.cpp	2016-01-26 14:44:02.000000000 -0800
-@@ -50,13 +50,14 @@
- // and back-end code generation options are specified with the target machine.
- //
- static cl::opt<std::string>
--InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
-+InputFilename(cl::Positional, cl::desc("<input bitcode>"),
-+              cl::init(std::string("-")));
- 
- static cl::opt<std::string>
- OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
- 
- static cl::opt<unsigned>
--TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
-+TimeCompilations("time-compilations", cl::Hidden, cl::init(1U),
-                  cl::value_desc("N"),
-                  cl::desc("Repeat compilation N times for timing"));
- 
-@@ -65,13 +66,15 @@
-                       cl::desc("Disable integrated assembler"));
- 
- // Determine optimization level.
-+// ORIGINAL:
- static cl::opt<char>
- OptLevel("O",
-          cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
-                   "(default = '-O2')"),
-          cl::Prefix,
--         cl::ZeroOrMore,
--         cl::init(' '));
-+         cl::Optional,
-+         cl::ValueRequired,
-+         cl::init('2'));
- 
- static cl::opt<std::string>
- TargetTriple("mtriple", cl::desc("Override target triple for module"));
---- tools/llvm-as/llvm-as.cpp	2014-08-25 11:16:47.000000000 -0700
-+++ tools/llvm-as/llvm-as.cpp	2016-01-26 15:07:18.000000000 -0800
-@@ -15,6 +15,8 @@
- //
- //===----------------------------------------------------------------------===//
- 
-+#include "llvm/Support/CommandLine.h"
-+
- #include "llvm/IR/LLVMContext.h"
- #include "llvm/AsmParser/Parser.h"
- #include "llvm/Bitcode/ReaderWriter.h"
-@@ -28,11 +30,21 @@
- #include "llvm/Support/SourceMgr.h"
- #include "llvm/Support/SystemUtils.h"
- #include "llvm/Support/ToolOutputFile.h"
--#include <memory>
- using namespace llvm;
- 
-+#include <memory>
-+#include <string>
-+
-+static cl::opt<std::string>
-+HiddenOption("h", cl::Hidden, cl::desc("hidden option"),
-+             cl::init(""));
-+
- static cl::opt<std::string>
--InputFilename(cl::Positional, cl::desc("<input .llvm file>"), cl::init("-"));
-+InputFilename(cl::Positional, cl::desc("<input file>"),
-+              cl::NotHidden,
-+              cl::Optional,
-+              cl::init(std::string("-")),
-+              cl::ValuePositionalNoArgs);
- 
- static cl::opt<std::string>
- OutputFilename("o", cl::desc("Override output filename"),
---- tools/llvm-dis/llvm-dis.cpp	2015-01-09 16:07:30.000000000 -0800
-+++ tools/llvm-dis/llvm-dis.cpp	2016-02-01 12:08:04.531107200 -0800
-@@ -38,7 +38,8 @@
- using namespace llvm;
- 
- static cl::opt<std::string>
--InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
-+InputFilename(cl::Positional, cl::desc("<input bitcode>"),
-+              cl::init(std::string("-")));
- 
- static cl::opt<std::string>
- OutputFilename("o", cl::desc("Override output filename"),
---- tools/bugpoint/OptimizerDriver.cpp	2014-11-07 13:30:36.000000000 -0800
-+++ tools/bugpoint/OptimizerDriver.cpp	2016-01-26 15:51:53.000000000 -0800
-@@ -46,7 +46,7 @@
-   // ChildOutput - This option captures the name of the child output file that
-   // is set up by the parent bugpoint process
-   cl::opt<std::string> ChildOutput("child-output", cl::ReallyHidden);
--  cl::opt<std::string> OptCmd("opt-command", cl::init(""),
-+  cl::opt<std::string> OptCmd("opt-command", cl::init(std::string("")),
-                               cl::desc("Path to opt. (default: search path "
-                                        "for 'opt'.)"));
- }
---- tools/opt/opt.cpp	2014-12-11 23:52:14.000000000 -0800
-+++ tools/opt/opt.cpp	2016-01-26 14:43:37.000000000 -0800
-@@ -72,7 +72,7 @@
- //
- static cl::opt<std::string>
- InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
--    cl::init("-"), cl::value_desc("filename"));
-+    cl::init(std::string("-")), cl::value_desc("filename"));
- 
- static cl::opt<std::string>
- OutputFilename("o", cl::desc("Override output filename"),
-@@ -175,7 +175,7 @@
- static cl::opt<std::string>
- DefaultDataLayout("default-data-layout",
-           cl::desc("data layout string to use if not specified by module"),
--          cl::value_desc("layout-string"), cl::init(""));
-+          cl::value_desc("layout-string"), cl::init(std::string("")));
- 
- 
- 
---- unittests/Support/CommandLineTest.cpp	2014-08-22 12:29:17.000000000 -0700
-+++ unittests/Support/CommandLineTest.cpp	2016-01-27 11:20:39.000000000 -0800
-@@ -7,12 +7,17 @@
- //
- //===----------------------------------------------------------------------===//
- 
-+#ifndef SKIP_ENVIRONMENT_TESTS
-+#define SKIP_ENVIRONMENT_TESTS 1
-+#endif
-+
- #include "llvm/ADT/STLExtras.h"
- #include "llvm/Config/config.h"
- #include "llvm/Support/CommandLine.h"
- #include "gtest/gtest.h"
- #include <stdlib.h>
- #include <string>
-+#include <vector>
- 
- using namespace llvm;
- 
-@@ -47,21 +52,23 @@
-   typedef cl::opt<T> Base;
- public:
-   // One option...
--  template<class M0t>
--  explicit StackOption(const M0t &M0) : Base(M0) {}
-+  template<typename T0>
-+  explicit StackOption(const T0 &M0) : cl::opt<T>(M0) { }
- 
-   // Two options...
--  template<class M0t, class M1t>
--  StackOption(const M0t &M0, const M1t &M1) : Base(M0, M1) {}
-+  template<typename T0, typename T1>
-+  explicit StackOption(const T0 &M0, const T1 &M1) : cl::opt<T>(M0, M1) { }
- 
-   // Three options...
--  template<class M0t, class M1t, class M2t>
--  StackOption(const M0t &M0, const M1t &M1, const M2t &M2) : Base(M0, M1, M2) {}
-+  template<typename T0, typename T1, typename T2>
-+  explicit StackOption(const T0 &M0, const T1 &M1, const T2 &M2)
-+  : cl::opt<T>(M0, M1, M2) { }
- 
-   // Four options...
--  template<class M0t, class M1t, class M2t, class M3t>
--  StackOption(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3)
--    : Base(M0, M1, M2, M3) {}
-+  template<typename T0, typename T1, typename T2, typename T3>
-+  explicit StackOption(const T0 &M0, const T1 &M1,
-+                       const T2 &M2, const T3 &M3)
-+  : cl::opt<T>(M0, M1, M2, M3) { }
- 
-   ~StackOption() {
-     this->removeArgument();
-@@ -112,7 +119,7 @@
- 
- const char test_env_var[] = "LLVM_TEST_COMMAND_LINE_FLAGS";
- 
--cl::opt<std::string> EnvironmentTestOption("env-test-opt");
-+static cl::opt<std::string> EnvironmentTestOption("env-test-opt");
- TEST(CommandLineTest, ParseEnvironment) {
-   TempEnvVar TEV(test_env_var, "-env-test-opt=hello");
-   EXPECT_EQ("", EnvironmentTestOption);
-@@ -153,12 +160,13 @@
- };
- 
- typedef void ParserFunction(StringRef Source, llvm::cl::StringSaver &Saver,
--                            SmallVectorImpl<const char *> &NewArgv,
-+                            std::vector<const char*> &NewArgv,
-                             bool MarkEOLs);
- 
- void testCommandLineTokenizer(ParserFunction *parse, const char *Input,
--                              const char *const Output[], size_t OutputSize) {
--  SmallVector<const char *, 0> Actual;
-+                              std::vector<const char*> &Output,
-+                              size_t OutputSize) {
-+  std::vector<const char*> Actual;
-   StrDupSaver Saver;
-   parse(Input, Saver, Actual, /*MarkEOLs=*/false);
-   EXPECT_EQ(OutputSize, Actual.size());
-@@ -175,7 +183,12 @@
-   const char *const Output[] = { "foo bar", "foo bar", "foo bar", "foo\\bar",
-                                  "foobarbaz", "C:\\src\\foo.cpp",
-                                  "C:\\src\\foo.cpp" };
--  testCommandLineTokenizer(cl::TokenizeGNUCommandLine, Input, Output,
-+
-+  std::vector<const char*> OutputVector;
-+  for (unsigned I = 0; I < array_lengthof(Output); ++I)
-+    OutputVector.push_back(Output[I]);
-+
-+  testCommandLineTokenizer(cl::TokenizeGNUCommandLine, Input, OutputVector,
-                            array_lengthof(Output));
- }
- 
-@@ -184,10 +197,17 @@
-                       "\"st \\\"u\" \\v";
-   const char *const Output[] = { "a\\b", "c\\\\d", "e\\f g", "h\"i", "j\\\"k",
-                                  "lmn", "o", "pqr", "st \"u", "\\v" };
--  testCommandLineTokenizer(cl::TokenizeWindowsCommandLine, Input, Output,
-+
-+  std::vector<const char*> OutputVector;
-+  for (unsigned I = 0; I < array_lengthof(Output); ++I)
-+    OutputVector.push_back(Output[I]);
-+
-+  testCommandLineTokenizer(cl::TokenizeWindowsCommandLine, Input, OutputVector,
-                            array_lengthof(Output));
- }
- 
-+#ifndef ALIAS_WITH_ARGUMENT_TESTS_ARE_BROKEN
-+// This test case is 100% broken.
- TEST(CommandLineTest, AliasesWithArguments) {
-   static const size_t ARGC = 3;
-   const char *const Inputs[][ARGC] = {
-@@ -201,7 +221,6 @@
-     StackOption<std::string> Actual("actual");
-     StackOption<bool> Extra("extra");
-     StackOption<std::string> Input(cl::Positional);
--
-     cl::alias Alias("alias", llvm::cl::aliasopt(Actual));
- 
-     cl::ParseCommandLineOptions(ARGC, Inputs[i]);
-@@ -211,6 +230,7 @@
-     Alias.removeArgument();
-   }
- }
-+#endif
- 
- void testAliasRequired(int argc, const char *const *argv) {
-   StackOption<std::string> Option("option", cl::Required);
---- utils/FileCheck/FileCheck.cpp	2014-11-18 18:56:00.000000000 -0800
-+++ utils/FileCheck/FileCheck.cpp	2016-02-01 13:52:04.699904440 -0800
-@@ -40,7 +40,8 @@
- 
- static cl::opt<std::string>
- InputFilename("input-file", cl::desc("File to check (defaults to stdin)"),
--              cl::init("-"), cl::value_desc("filename"));
-+              cl::value_desc("filename"),
-+              cl::init(std::string("-")));
- 
- static cl::list<std::string>
- CheckPrefixes("check-prefix",
---- include/llvm/LinkAllPasses.h	2015-01-14 03:23:27.000000000 -0800
-+++ include/llvm/LinkAllPasses.h	2016-02-01 09:24:47.493918163 -0800
-@@ -15,6 +15,7 @@
- #ifndef LLVM_LINKALLPASSES_H
- #define LLVM_LINKALLPASSES_H
- 
-+#include "llvm/Analysis/AliasAnalysis.h"
- #include "llvm/Analysis/AliasSetTracker.h"
- #include "llvm/Analysis/CallPrinter.h"
- #include "llvm/Analysis/DomPrinter.h"
-@@ -35,10 +36,12 @@
- #include "llvm/Transforms/Utils/SymbolRewriter.h"
- #include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
- #include "llvm/Transforms/Vectorize.h"
-+
- #include <cstdlib>
- 
- namespace {
-   struct ForcePassLinking {
-+    __attribute__((used, noinline))
-     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,
-@@ -47,6 +50,8 @@
-       if (std::getenv("bar") != (char*) -1)
-         return;
- 
-+      asm("");
-+
-       (void) llvm::createAAEvalPass();
-       (void) llvm::createAggressiveDCEPass();
-       (void) llvm::createAliasAnalysisCounterPass();
-@@ -148,9 +153,13 @@
-       (void) llvm::createMetaRenamerPass();
-       (void) llvm::createFunctionAttrsPass();
-       (void) llvm::createMergeFunctionsPass();
--      (void) llvm::createPrintModulePass(*(llvm::raw_ostream*)nullptr);
--      (void) llvm::createPrintFunctionPass(*(llvm::raw_ostream*)nullptr);
--      (void) llvm::createPrintBasicBlockPass(*(llvm::raw_ostream*)nullptr);
-+
-+      std::string S;
-+      llvm::raw_string_ostream RSO(S);
-+
-+      (void) llvm::createPrintModulePass(RSO);
-+      (void) llvm::createPrintFunctionPass(RSO);
-+      (void) llvm::createPrintBasicBlockPass(RSO);
-       (void) llvm::createModuleDebugInfoPrinterPass();
-       (void) llvm::createPartialInliningPass();
-       (void) llvm::createLintPass();
-@@ -167,13 +176,20 @@
-       (void) llvm::createSeparateConstOffsetFromGEPPass();
-       (void) llvm::createRewriteSymbolsPass();
- 
--      (void)new llvm::IntervalPartition();
--      (void)new llvm::ScalarEvolution();
--      ((llvm::Function*)nullptr)->viewCFGOnly();
-+      llvm::IntervalPartition *LIP = new llvm::IntervalPartition();
-+      (void) LIP;
-+
-+      llvm::ScalarEvolution *LSE = new llvm::ScalarEvolution();
-+      (void) LSE;
-+
-+      llvm::Function *F =
-+        llvm::Function::Create(nullptr, llvm::GlobalValue::ExternalLinkage);
-+      F->viewCFGOnly();
-+
-       llvm::RGPassManager RGM;
--      ((llvm::RegionPass*)nullptr)->runOnRegion((llvm::Region*)nullptr, RGM);
--      llvm::AliasSetTracker X(*(llvm::AliasAnalysis*)nullptr);
--      X.add(nullptr, 0, llvm::AAMDNodes()); // for -print-alias-sets
-+      llvm::AliasAnalysis LAA;
-+      llvm::AliasSetTracker LAST(LAA);
-+      LAST.add(nullptr, 0, llvm::AAMDNodes()); // for -print-alias-sets
-     }
-   } ForcePassLinking; // Force link by creating a global definition.
- }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/016-solaris-clang-tools-libclang.patch	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,134 @@
+# Miscellaneous fixes.
+# 3.9.X upstream.
+--- tools/clang/tools/libclang/CXLoadedDiagnostic.cpp	2015-10-20 09:23:58.000000000 -0400
++++ tools/clang/tools/libclang/CXLoadedDiagnostic.cpp	2016-05-28 16:46:50.786462237 -0400
+@@ -190,8 +190,8 @@
+ class DiagLoader : serialized_diags::SerializedDiagnosticReader {
+   enum CXLoadDiag_Error *error;
+   CXString *errorString;
+-  std::unique_ptr<CXLoadedDiagnosticSetImpl> TopDiags;
+-  SmallVector<std::unique_ptr<CXLoadedDiagnostic>, 8> CurrentDiags;
++  std::shared_ptr<CXLoadedDiagnosticSetImpl> TopDiags;
++  std::vector<std::shared_ptr<CXLoadedDiagnostic> > CurrentDiags;
+ 
+   std::error_code reportBad(enum CXLoadDiag_Error code, llvm::StringRef err) {
+     if (error)
+@@ -250,7 +250,7 @@
+ } // end anonymous namespace
+ 
+ CXDiagnosticSet DiagLoader::load(const char *file) {
+-  TopDiags = llvm::make_unique<CXLoadedDiagnosticSetImpl>();
++  TopDiags = std::make_shared<CXLoadedDiagnosticSetImpl>();
+ 
+   std::error_code EC = readDiagnostics(file);
+   if (EC) {
+@@ -268,7 +268,7 @@
+     return nullptr;
+   }
+ 
+-  return (CXDiagnosticSet)TopDiags.release();
++  return (CXDiagnosticSet)TopDiags.get();
+ }
+ 
+ std::error_code
+@@ -309,16 +309,18 @@
+ }
+ 
+ std::error_code DiagLoader::visitStartOfDiagnostic() {
+-  CurrentDiags.push_back(llvm::make_unique<CXLoadedDiagnostic>());
++  CurrentDiags.push_back(std::make_shared<CXLoadedDiagnostic>());
+   return std::error_code();
+ }
+ 
+ std::error_code DiagLoader::visitEndOfDiagnostic() {
+-  auto D = CurrentDiags.pop_back_val();
++  std::shared_ptr<CXLoadedDiagnostic> D = CurrentDiags.back();
+   if (CurrentDiags.empty())
+-    TopDiags->appendDiagnostic(std::move(D));
++    TopDiags->appendDiagnostic(D);
+   else
+-    CurrentDiags.back()->getChildDiagnostics().appendDiagnostic(std::move(D));
++    CurrentDiags.back()->getChildDiagnostics().appendDiagnostic(D);
++
++  CurrentDiags.pop_back();
+   return std::error_code();
+ }
+ 
+###
+--- tools/clang/tools/libclang/CIndexDiagnostic.h	2015-10-20 09:23:58.000000000 -0400
++++ tools/clang/tools/libclang/CIndexDiagnostic.h	2016-05-28 16:49:40.739768269 -0400
+@@ -25,7 +25,7 @@
+ class CXDiagnosticImpl;
+   
+ class CXDiagnosticSetImpl {
+-  std::vector<std::unique_ptr<CXDiagnosticImpl>> Diagnostics;
++  std::vector<std::shared_ptr<CXDiagnosticImpl>> Diagnostics;
+   const bool IsExternallyManaged;
+ public:
+   CXDiagnosticSetImpl(bool isManaged = false)
+@@ -42,7 +42,7 @@
+     return Diagnostics[i].get();
+   }
+ 
+-  void appendDiagnostic(std::unique_ptr<CXDiagnosticImpl> D);
++  void appendDiagnostic(std::shared_ptr<CXDiagnosticImpl> D);
+ 
+   bool empty() const {
+     return Diagnostics.empty();
+@@ -99,8 +99,8 @@
+   CXDiagnosticImpl(Kind k) : K(k) {}
+   CXDiagnosticSetImpl ChildDiags;
+ 
+-  void append(std::unique_ptr<CXDiagnosticImpl> D) {
+-    ChildDiags.appendDiagnostic(std::move(D));
++  void append(std::shared_ptr<CXDiagnosticImpl> D) {
++    ChildDiags.appendDiagnostic(D);
+   }
+   
+ private:
+###
+--- tools/clang/tools/libclang/CIndexDiagnostic.cpp	2015-10-20 09:23:58.000000000 -0400
++++ tools/clang/tools/libclang/CIndexDiagnostic.cpp	2016-05-28 16:53:14.353165739 -0400
+@@ -33,8 +33,8 @@
+ CXDiagnosticSetImpl::~CXDiagnosticSetImpl() {}
+ 
+ void
+-CXDiagnosticSetImpl::appendDiagnostic(std::unique_ptr<CXDiagnosticImpl> D) {
+-  Diagnostics.push_back(std::move(D));
++CXDiagnosticSetImpl::appendDiagnostic(std::shared_ptr<CXDiagnosticImpl> D) {
++  Diagnostics.push_back(D);
+ }
+ 
+ CXDiagnosticImpl::~CXDiagnosticImpl() {}
+@@ -104,9 +104,10 @@
+     if (Level != DiagnosticsEngine::Note)
+       CurrentSet = MainSet;
+ 
+-    auto Owner = llvm::make_unique<CXStoredDiagnostic>(*SD, LangOpts);
+-    CXStoredDiagnostic &CD = *Owner;
+-    CurrentSet->appendDiagnostic(std::move(Owner));
++    std::shared_ptr<CXStoredDiagnostic> Owner =
++      std::make_shared<CXStoredDiagnostic>(*SD, LangOpts);
++    CXStoredDiagnostic &CD = *Owner.get();
++    CurrentSet->appendDiagnostic(Owner);
+ 
+     if (Level != DiagnosticsEngine::Note)
+       CurrentSet = &CD.getChildDiagnostics();
+@@ -127,7 +128,7 @@
+     else
+       L = clang_getNullLocation();
+     CurrentSet->appendDiagnostic(
+-        llvm::make_unique<CXDiagnosticCustomNoteImpl>(Message, L));
++        std::make_shared<CXDiagnosticCustomNoteImpl>(Message, L));
+   }
+ 
+   void emitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc,
+@@ -149,7 +150,7 @@
+     else
+       L = clang_getNullLocation();
+     CurrentSet->appendDiagnostic(
+-        llvm::make_unique<CXDiagnosticCustomNoteImpl>(Message, L));
++        std::make_shared<CXDiagnosticCustomNoteImpl>(Message, L));
+   }
+ 
+   CXDiagnosticSetImpl *CurrentSet;
--- a/components/llvm/patches/017-lli-21870067.patch	Thu Jul 28 16:15:45 2016 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,229 +0,0 @@
-# 21870067 lli makes incorrect assumptions about anonymous namespace instantiation order
-# 21870087 naming convention for the InputFile key is inconsistent across LLVM utilities
-# For upstream - maybe.
---- tools/lli/lli.cpp	2014-12-02 16:51:19.000000000 -0800
-+++ tools/lli/lli.cpp	2015-09-20 10:37:39.445573121 -0700
-@@ -63,21 +63,22 @@
- 
- #define DEBUG_TYPE "lli"
- 
--namespace {
--  cl::opt<std::string>
-+static cl::opt<std::string>
-   InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
- 
--  cl::list<std::string>
-+static cl::list<std::string>
-   InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
- 
--  cl::opt<bool> ForceInterpreter("force-interpreter",
-+static cl::opt<bool>
-+ForceInterpreter("force-interpreter",
-                                  cl::desc("Force interpretation: disable JIT"),
-                                  cl::init(false));
- 
-   // The MCJIT supports building for a target address space separate from
-   // the JIT compilation process. Use a forked process and a copying
-   // memory manager with IPC to execute using this functionality.
--  cl::opt<bool> RemoteMCJIT("remote-mcjit",
-+static cl::opt<bool>
-+RemoteMCJIT("remote-mcjit",
-     cl::desc("Execute MCJIT'ed code in a separate process."),
-     cl::init(false));
- 
-@@ -85,7 +86,7 @@
-   // the simulated remote execution that allocates address space for child
-   // execution. The child process will be executed and will communicate with
-   // lli via stdin/stdout pipes.
--  cl::opt<std::string>
-+static cl::opt<std::string>
-   ChildExecPath("mcjit-remote-process",
-                 cl::desc("Specify the filename of the process to launch "
-                          "for remote MCJIT execution.  If none is specified,"
-@@ -93,7 +94,7 @@
-                 cl::value_desc("filename"), cl::init(""));
- 
-   // Determine optimization level.
--  cl::opt<char>
-+static cl::opt<char>
-   OptLevel("O",
-            cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
-                     "(default = '-O2')"),
-@@ -101,73 +102,73 @@
-            cl::ZeroOrMore,
-            cl::init(' '));
- 
--  cl::opt<std::string>
-+static cl::opt<std::string>
-   TargetTriple("mtriple", cl::desc("Override target triple for module"));
- 
--  cl::opt<std::string>
-+static cl::opt<std::string>
-   MArch("march",
-         cl::desc("Architecture to generate assembly for (see --version)"));
- 
--  cl::opt<std::string>
-+static cl::opt<std::string>
-   MCPU("mcpu",
-        cl::desc("Target a specific cpu type (-mcpu=help for details)"),
-        cl::value_desc("cpu-name"),
-        cl::init(""));
- 
--  cl::list<std::string>
-+static cl::list<std::string>
-   MAttrs("mattr",
-          cl::CommaSeparated,
-          cl::desc("Target specific attributes (-mattr=help for details)"),
-          cl::value_desc("a1,+a2,-a3,..."));
- 
--  cl::opt<std::string>
-+static cl::opt<std::string>
-   EntryFunc("entry-function",
-             cl::desc("Specify the entry function (default = 'main') "
-                      "of the executable"),
-             cl::value_desc("function"),
-             cl::init("main"));
- 
--  cl::list<std::string>
-+static cl::list<std::string>
-   ExtraModules("extra-module",
-          cl::desc("Extra modules to be loaded"),
-          cl::value_desc("input bitcode"));
- 
--  cl::list<std::string>
-+static cl::list<std::string>
-   ExtraObjects("extra-object",
-          cl::desc("Extra object files to be loaded"),
-          cl::value_desc("input object"));
- 
--  cl::list<std::string>
-+static cl::list<std::string>
-   ExtraArchives("extra-archive",
-          cl::desc("Extra archive files to be loaded"),
-          cl::value_desc("input archive"));
- 
--  cl::opt<bool>
-+static cl::opt<bool>
-   EnableCacheManager("enable-cache-manager",
-         cl::desc("Use cache manager to save/load mdoules"),
-         cl::init(false));
- 
--  cl::opt<std::string>
-+static cl::opt<std::string>
-   ObjectCacheDir("object-cache-dir",
-                   cl::desc("Directory to store cached object files "
-                            "(must be user writable)"),
-                   cl::init(""));
- 
--  cl::opt<std::string>
-+static cl::opt<std::string>
-   FakeArgv0("fake-argv0",
-             cl::desc("Override the 'argv[0]' value passed into the executing"
-                      " program"), cl::value_desc("executable"));
- 
--  cl::opt<bool>
-+static cl::opt<bool>
-   DisableCoreFiles("disable-core-files", cl::Hidden,
-                    cl::desc("Disable emission of core files if possible"));
- 
--  cl::opt<bool>
-+static cl::opt<bool>
-   NoLazyCompilation("disable-lazy-compilation",
-                   cl::desc("Disable JIT lazy compilation"),
-                   cl::init(false));
- 
--  cl::opt<Reloc::Model>
-+static cl::opt<Reloc::Model>
-   RelocModel("relocation-model",
-              cl::desc("Choose relocation model"),
-              cl::init(Reloc::Default),
-@@ -182,7 +183,7 @@
-                        "Relocatable external references, non-relocatable code"),
-             clEnumValEnd));
- 
--  cl::opt<llvm::CodeModel::Model>
-+static cl::opt<llvm::CodeModel::Model>
-   CMModel("code-model",
-           cl::desc("Choose code model"),
-           cl::init(CodeModel::JITDefault),
-@@ -198,12 +199,12 @@
-                                 "Large code model"),
-                      clEnumValEnd));
- 
--  cl::opt<bool>
-+static cl::opt<bool>
-   GenerateSoftFloatCalls("soft-float",
-     cl::desc("Generate software floating point library calls"),
-     cl::init(false));
- 
--  cl::opt<llvm::FloatABI::ABIType>
-+static cl::opt<llvm::FloatABI::ABIType>
-   FloatABIForCalls("float-abi",
-                    cl::desc("Choose float ABI type"),
-                    cl::init(FloatABI::Default),
-@@ -215,7 +216,7 @@
-                      clEnumValN(FloatABI::Hard, "hard",
-                                 "Hard float ABI (uses FP registers)"),
-                      clEnumValEnd));
--  cl::opt<bool>
-+static cl::opt<bool>
- // In debug builds, make this default to true.
- #ifdef NDEBUG
- #define EMIT_DEBUG false
-@@ -232,7 +233,6 @@
-     cl::Hidden,
-     cl::desc("Emit debug info objfiles to disk"),
-     cl::init(false));
--}
- 
- //===----------------------------------------------------------------------===//
- // Object cache
---- tools/lli/lli.cpp	2015-10-05 11:01:32.000000000 -0700
-+++ tools/lli/lli.cpp	2016-01-26 14:44:39.000000000 -0800
-@@ -64,7 +64,8 @@
- #define DEBUG_TYPE "lli"
- 
- static cl::opt<std::string>
--  InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
-+  InputFile(cl::desc("<input bitcode>"), cl::Positional,
-+            cl::init(std::string("-")));
- 
- static cl::list<std::string>
-   InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
-@@ -91,7 +92,8 @@
-                 cl::desc("Specify the filename of the process to launch "
-                          "for remote MCJIT execution.  If none is specified,"
-                          "\n\tremote execution will be simulated in-process."),
--                cl::value_desc("filename"), cl::init(""));
-+                cl::value_desc("filename"),
-+                cl::init(std::string("")));
- 
-   // Determine optimization level.
- static cl::opt<char>
-@@ -113,7 +115,7 @@
-   MCPU("mcpu",
-        cl::desc("Target a specific cpu type (-mcpu=help for details)"),
-        cl::value_desc("cpu-name"),
--       cl::init(""));
-+       cl::init(std::string("")));
- 
- static cl::list<std::string>
-   MAttrs("mattr",
-@@ -126,7 +128,7 @@
-             cl::desc("Specify the entry function (default = 'main') "
-                      "of the executable"),
-             cl::value_desc("function"),
--            cl::init("main"));
-+            cl::init(std::string("main")));
- 
- static cl::list<std::string>
-   ExtraModules("extra-module",
-@@ -152,7 +154,7 @@
-   ObjectCacheDir("object-cache-dir",
-                   cl::desc("Directory to store cached object files "
-                            "(must be user writable)"),
--                  cl::init(""));
-+                  cl::init(std::string("")));
- 
- static cl::opt<std::string>
-   FakeArgv0("fake-argv0",
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/017-solaris-clang-tools-tablegen.patch	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,31 @@
+# 24314638 LLVM CommandLine subsystem is busted
+# 3.9.X for upstrea.
+--- tools/clang/utils/TableGen/TableGen.cpp	2016-01-03 23:51:46.000000000 -0500
++++ tools/clang/utils/TableGen/TableGen.cpp	2016-05-08 23:19:20.578431871 -0400
+@@ -56,8 +56,7 @@
+   GenAttrDocs
+ };
+ 
+-namespace {
+-cl::opt<ActionType> Action(
++static cl::opt<ActionType> Action(
+     cl::desc("Action to perform:"),
+     cl::values(
+         clEnumValN(GenClangAttrClasses, "gen-clang-attr-classes",
+@@ -136,7 +135,7 @@
+                    "Generate attribute documentation"),
+         clEnumValEnd));
+ 
+-cl::opt<std::string>
++static cl::opt<std::string>
+ ClangComponent("clang-component",
+                cl::desc("Only use warnings from specified component"),
+                cl::value_desc("component"), cl::Hidden);
+@@ -238,7 +237,6 @@
+ 
+   return false;
+ }
+-}
+ 
+ int main(int argc, char **argv) {
+   sys::PrintStackTraceOnErrorSignal();
--- a/components/llvm/patches/018-21870283-llvm-GetArgumentVector.patch	Thu Jul 28 16:15:45 2016 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,49 +0,0 @@
-# 21870283 - llvm::sys::Process::GetArgumentVector should overload
-# for std::vector
-# For upstream - maybe.
---- include/llvm/Support/Process.h	2014-12-04 08:59:36.000000000 -0800
-+++ include/llvm/Support/Process.h	2015-09-20 16:56:49.207515143 -0700
-@@ -81,20 +81,26 @@
-                                              const std::string& FileName);
- 
-   /// This function returns a SmallVector containing the arguments passed from
-   /// the operating system to the program.  This function expects to be handed
-   /// the vector passed in from main.
-   static std::error_code
-   GetArgumentVector(SmallVectorImpl<const char *> &Args,
-                     ArrayRef<const char *> ArgsFromMain,
-                     SpecificBumpPtrAllocator<char> &ArgAllocator);
- 
-+  /// Overload the above for a std::vector, and without the
-+  // useless SpecificBumpPtrAllocator argument.
-+  static std::error_code
-+  GetArgumentVector(std::vector<const char *> &ArgsOut,
-+                    ArrayRef<const char *> ArgsIn);
-+
-   // This functions ensures that the standard file descriptors (input, output,
-   // and error) are properly mapped to a file descriptor before we use any of
-   // them.  This should only be called by standalone programs, library
-   // components should not call this.
-   static std::error_code FixupStandardFileDescriptors();
- 
-   // This function safely closes a file descriptor.  It is not safe to retry
-   // close(2) when it returns with errno equivalent to EINTR; this is because
-   // *nixen cannot agree if the file descriptor is, in fact, closed when this
-   // occurs.
---- lib/Support/Unix/Process.inc	2014-12-04 08:59:36.000000000 -0800
-+++ lib/Support/Unix/Process.inc	2015-09-20 17:11:29.527153186 -0700
-@@ -180,6 +180,14 @@
-   return std::error_code();
- }
- 
-+std::error_code
-+Process::GetArgumentVector(std::vector<const char *> &ArgsOut,
-+                           ArrayRef<const char *> ArgsIn) {
-+  ArgsOut.insert(ArgsOut.end(), ArgsIn.begin(), ArgsIn.end());
-+
-+  return std::error_code();
-+}
-+
- namespace {
- class FDCloser {
- public:
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/018-solaris-LLVM-utils-tablegen.patch	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,118 @@
+# 24314638 LLVM CommandLine subsystem is busted
+# 3.9.X for upstream.
+--- utils/TableGen/AsmMatcherEmitter.cpp	2016-01-03 02:33:39.000000000 -0500
++++ utils/TableGen/AsmMatcherEmitter.cpp	2016-05-08 23:19:20.581431944 -0400
+@@ -121,7 +121,7 @@
+ #define DEBUG_TYPE "asm-matcher-emitter"
+ 
+ static cl::opt<std::string>
+-MatchPrefix("match-prefix", cl::init(""),
++MatchPrefix("match-prefix", cl::init(std::string("")),
+             cl::desc("Only match instructions with the given prefix"));
+ 
+ namespace {
+--- utils/TableGen/TableGen.cpp	2016-01-03 23:51:51.000000000 -0500
++++ utils/TableGen/TableGen.cpp	2016-05-08 23:19:20.582431969 -0400
+@@ -46,55 +46,55 @@
+   GenAttributes
+ };
+ 
+-namespace {
+-  cl::opt<ActionType>
+-  Action(cl::desc("Action to perform:"),
+-         cl::values(clEnumValN(PrintRecords, "print-records",
+-                               "Print all records to stdout (default)"),
+-                    clEnumValN(GenEmitter, "gen-emitter",
+-                               "Generate machine code emitter"),
+-                    clEnumValN(GenRegisterInfo, "gen-register-info",
+-                               "Generate registers and register classes info"),
+-                    clEnumValN(GenInstrInfo, "gen-instr-info",
+-                               "Generate instruction descriptions"),
+-                    clEnumValN(GenCallingConv, "gen-callingconv",
+-                               "Generate calling convention descriptions"),
+-                    clEnumValN(GenAsmWriter, "gen-asm-writer",
+-                               "Generate assembly writer"),
+-                    clEnumValN(GenDisassembler, "gen-disassembler",
+-                               "Generate disassembler"),
+-                    clEnumValN(GenPseudoLowering, "gen-pseudo-lowering",
+-                               "Generate pseudo instruction lowering"),
+-                    clEnumValN(GenAsmMatcher, "gen-asm-matcher",
+-                               "Generate assembly instruction matcher"),
+-                    clEnumValN(GenDAGISel, "gen-dag-isel",
+-                               "Generate a DAG instruction selector"),
+-                    clEnumValN(GenDFAPacketizer, "gen-dfa-packetizer",
+-                               "Generate DFA Packetizer for VLIW targets"),
+-                    clEnumValN(GenFastISel, "gen-fast-isel",
+-                               "Generate a \"fast\" instruction selector"),
+-                    clEnumValN(GenSubtarget, "gen-subtarget",
+-                               "Generate subtarget enumerations"),
+-                    clEnumValN(GenIntrinsic, "gen-intrinsic",
+-                               "Generate intrinsic information"),
+-                    clEnumValN(GenTgtIntrinsic, "gen-tgt-intrinsic",
+-                               "Generate target intrinsic information"),
+-                    clEnumValN(PrintEnums, "print-enums",
+-                               "Print enum values for a class"),
+-                    clEnumValN(PrintSets, "print-sets",
+-                               "Print expanded sets for testing DAG exprs"),
+-                    clEnumValN(GenOptParserDefs, "gen-opt-parser-defs",
+-                               "Generate option definitions"),
+-                    clEnumValN(GenCTags, "gen-ctags",
+-                               "Generate ctags-compatible index"),
+-                    clEnumValN(GenAttributes, "gen-attrs",
+-                               "Generate attributes"),
+-                    clEnumValEnd));
++static cl::opt<ActionType>
++Action(cl::desc("Action to perform:"),
++       cl::values(clEnumValN(PrintRecords, "print-records",
++                             "Print all records to stdout (default)"),
++                  clEnumValN(GenEmitter, "gen-emitter",
++                             "Generate machine code emitter"),
++                  clEnumValN(GenRegisterInfo, "gen-register-info",
++                             "Generate registers and register classes info"),
++                  clEnumValN(GenInstrInfo, "gen-instr-info",
++                             "Generate instruction descriptions"),
++                  clEnumValN(GenCallingConv, "gen-callingconv",
++                             "Generate calling convention descriptions"),
++                  clEnumValN(GenAsmWriter, "gen-asm-writer",
++                             "Generate assembly writer"),
++                  clEnumValN(GenDisassembler, "gen-disassembler",
++                             "Generate disassembler"),
++                  clEnumValN(GenPseudoLowering, "gen-pseudo-lowering",
++                             "Generate pseudo instruction lowering"),
++                  clEnumValN(GenAsmMatcher, "gen-asm-matcher",
++                             "Generate assembly instruction matcher"),
++                  clEnumValN(GenDAGISel, "gen-dag-isel",
++                             "Generate a DAG instruction selector"),
++                  clEnumValN(GenDFAPacketizer, "gen-dfa-packetizer",
++                             "Generate DFA Packetizer for VLIW targets"),
++                  clEnumValN(GenFastISel, "gen-fast-isel",
++                             "Generate a \"fast\" instruction selector"),
++                  clEnumValN(GenSubtarget, "gen-subtarget",
++                             "Generate subtarget enumerations"),
++                  clEnumValN(GenIntrinsic, "gen-intrinsic",
++                             "Generate intrinsic information"),
++                  clEnumValN(GenTgtIntrinsic, "gen-tgt-intrinsic",
++                             "Generate target intrinsic information"),
++                  clEnumValN(PrintEnums, "print-enums",
++                             "Print enum values for a class"),
++                  clEnumValN(PrintSets, "print-sets",
++                             "Print expanded sets for testing DAG exprs"),
++                  clEnumValN(GenOptParserDefs, "gen-opt-parser-defs",
++                             "Generate option definitions"),
++                  clEnumValN(GenCTags, "gen-ctags",
++                             "Generate ctags-compatible index"),
++                  clEnumValN(GenAttributes, "gen-attrs",
++                             "Generate attributes"),
++                  clEnumValEnd));
+ 
+-  cl::opt<std::string>
+-  Class("class", cl::desc("Print Enum list for this class"),
+-          cl::value_desc("class name"));
++static cl::opt<std::string>
++Class("class", cl::desc("Print Enum list for this class"),
++      cl::value_desc("class name"));
+ 
++namespace {
+ bool LLVMTableGenMain(raw_ostream &OS, RecordKeeper &Records) {
+   switch (Action) {
+   case PrintRecords:
--- a/components/llvm/patches/019-21870099-clang.patch	Thu Jul 28 16:15:45 2016 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,174 +0,0 @@
-# 21870099 - 128 bytes for a filesystem path is definitely not enough
-# 21870283 - llvm::sys::Process::GetArgumentVector should overload for
-# std::vector
-# For upstream - maybe.
---- tools/clang/tools/driver/driver.cpp	2015-09-20 11:19:37.402058833 -0700
-+++ tools/clang/tools/driver/driver.cpp	2015-09-20 17:00:21.850124658 -0700
-@@ -89,21 +89,21 @@
- ///  and the following argument.
- ///
- ///  'Ox': Removes all flags matching 'O' or 'O[sz0-9]' and adds 'Ox'
- ///  at the end of the command line.
- ///
- /// \param OS - The stream to write edit information to.
- /// \param Args - The vector of command line arguments.
- /// \param Edit - The override command to perform.
- /// \param SavedStrings - Set to use for storing string representations.
- static void ApplyOneQAOverride(raw_ostream &OS,
--                               SmallVectorImpl<const char*> &Args,
-+                               std::vector<const char*> &Args,
-                                StringRef Edit,
-                                std::set<std::string> &SavedStrings) {
-   // This does not need to be efficient.
- 
-   if (Edit[0] == '^') {
-     const char *Str =
-       GetStableCStr(SavedStrings, Edit.substr(1));
-     OS << "### Adding argument " << Str << " at beginning\n";
-     Args.insert(Args.begin() + 1, Str);
-   } else if (Edit[0] == '+') {
-@@ -161,21 +161,21 @@
-     }
-     OS << "### Adding argument " << Edit << " at end\n";
-     Args.push_back(GetStableCStr(SavedStrings, '-' + Edit.str()));
-   } else {
-     OS << "### Unrecognized edit: " << Edit << "\n";
-   }
- }
- 
- /// ApplyQAOverride - Apply a comma separate list of edits to the
- /// input argument lists. See ApplyOneQAOverride.
--static void ApplyQAOverride(SmallVectorImpl<const char*> &Args,
-+static void ApplyQAOverride(std::vector<const char*> &Args,
-                             const char *OverrideStr,
-                             std::set<std::string> &SavedStrings) {
-   raw_ostream *OS = &llvm::errs();
- 
-   if (OverrideStr[0] == '#') {
-     ++OverrideStr;
-     OS = &llvm::nulls();
-   }
- 
-   *OS << "### CCC_OVERRIDE_OPTIONS: " << OverrideStr << "\n";
-@@ -223,21 +223,21 @@
-       {"cl", "--driver-mode=cl"},
-       {"++", "--driver-mode=g++"},
-   };
- 
-   for (size_t i = 0; i < llvm::array_lengthof(DriverSuffixes); ++i)
-     if (ProgName.endswith(DriverSuffixes[i].Suffix))
-       return &DriverSuffixes[i];
-   return nullptr;
- }
- 
--static void ParseProgName(SmallVectorImpl<const char *> &ArgVector,
-+static void ParseProgName(std::vector<const char *> &ArgVector,
-                           std::set<std::string> &SavedStrings) {
-   // Try to infer frontend type and default target from the program name by
-   // comparing it against DriverSuffixes in order.
- 
-   // If there is a match, the function tries to identify a target as prefix.
-   // E.g. "x86_64-linux-clang" as interpreted as suffix "clang" with target
-   // prefix "x86_64-linux". If such a target prefix is found, is gets added via
-   // -target as implicit first argument.
- 
-   std::string ProgName =llvm::sys::path::stem(ArgVector[0]);
-@@ -325,39 +325,40 @@
-   // use clang-cl.exe as the prefix to avoid confusion between clang and MSVC.
-   StringRef ExeBasename(llvm::sys::path::filename(Path));
-   if (ExeBasename.equals_lower("cl.exe"))
-     ExeBasename = "clang-cl.exe";
-   DiagClient->setPrefix(ExeBasename);
- }
- 
- // This lets us create the DiagnosticsEngine with a properly-filled-out
- // DiagnosticOptions instance.
- static DiagnosticOptions *
--CreateAndPopulateDiagOpts(SmallVectorImpl<const char *> &argv) {
--  auto *DiagOpts = new DiagnosticOptions;
-+CreateAndPopulateDiagOpts(std::vector<const char *> &argv) {
-+  auto *DiagOpts = new DiagnosticOptions();
-   std::unique_ptr<OptTable> Opts(createDriverOptTable());
-   unsigned MissingArgIndex, MissingArgCount;
-   std::unique_ptr<InputArgList> Args(Opts->ParseArgs(
--      argv.begin() + 1, argv.end(), MissingArgIndex, MissingArgCount));
-+      argv.data() + 1, argv.data() + argv.size(), MissingArgIndex,
-+      MissingArgCount));
-   // We ignore MissingArgCount and the return value of ParseDiagnosticArgs.
-   // Any errors that would be diagnosed here will also be diagnosed later,
-   // when the DiagnosticsEngine actually exists.
-   (void) ParseDiagnosticArgs(*DiagOpts, *Args);
-   return DiagOpts;
- }
- 
--static void SetInstallDir(SmallVectorImpl<const char *> &argv,
-+static void SetInstallDir(std::vector<const char *> &argv,
-                           Driver &TheDriver) {
-   // Attempt to find the original path used to invoke the driver, to determine
-   // the installed path. We do this manually, because we want to support that
-   // path being a symlink.
--  SmallString<128> InstalledPath(argv[0]);
-+  SmallString<PATH_MAX> InstalledPath(argv[0]);
- 
-   // Do a PATH lookup, if there are no directory components.
-   if (llvm::sys::path::filename(InstalledPath) == InstalledPath)
-     if (llvm::ErrorOr<std::string> Tmp = llvm::sys::findProgramByName(
-             llvm::sys::path::filename(InstalledPath.str())))
-       InstalledPath = *Tmp;
-   llvm::sys::fs::make_absolute(InstalledPath);
-   InstalledPath = llvm::sys::path::parent_path(InstalledPath);
-   if (llvm::sys::fs::exists(InstalledPath.c_str()))
-     TheDriver.setInstalledDir(InstalledPath);
-@@ -375,24 +376,26 @@
-   return 1;
- }
- 
- int main(int argc_, const char **argv_) {
-   llvm::sys::PrintStackTraceOnErrorSignal();
-   llvm::PrettyStackTraceProgram X(argc_, argv_);
- 
-   if (llvm::sys::Process::FixupStandardFileDescriptors())
-     return 1;
- 
--  SmallVector<const char *, 256> argv;
-+  std::vector<const char*> argv;
-   llvm::SpecificBumpPtrAllocator<char> ArgAllocator;
--  std::error_code EC = llvm::sys::Process::GetArgumentVector(
--      argv, llvm::makeArrayRef(argv_, argc_), ArgAllocator);
-+  llvm::ArrayRef<const char*> AAR = llvm::makeArrayRef(argv_, argc_);
-+  std::error_code EC =
-+    llvm::sys::Process::GetArgumentVector(argv, AAR);
-+
-   if (EC) {
-     llvm::errs() << "error: couldn't get arguments: " << EC.message() << '\n';
-     return 1;
-   }
- 
-   std::set<std::string> SavedStrings;
-   StringSetSaver Saver(SavedStrings);
- 
-   // Determines whether we want nullptr markers in argv to indicate response
-   // files end-of-lines. We only use this for the /LINK driver argument.
-@@ -459,21 +462,21 @@
-   Driver TheDriver(Path, llvm::sys::getDefaultTargetTriple(), Diags);
-   SetInstallDir(argv, TheDriver);
- 
-   llvm::InitializeAllTargets();
-   ParseProgName(argv, SavedStrings);
- 
-   SetBackdoorDriverOutputsFromEnvVars(TheDriver);
- 
-   std::unique_ptr<Compilation> C(TheDriver.BuildCompilation(argv));
-   int Res = 0;
--  SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
-+  SmallVector<std::pair<int, const Command *>, 8> FailingCommands;
-   if (C.get())
-     Res = TheDriver.ExecuteCompilation(*C, FailingCommands);
- 
-   // Force a crash to test the diagnostics.
-   if (::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH")) {
-     Diags.Report(diag::err_drv_force_crash) << "FORCE_CLANG_DIAGNOSTICS_CRASH";
- 
-     // Pretend that every command failed.
-     FailingCommands.clear();
-     for (const auto &J : C->getJobs())
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/019-solaris-LLVM-utils-filecheck.patch	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,13 @@
+# 24314638 LLVM CommandLine subsystem is busted
+# 3.9.X for upstream.
+--- utils/FileCheck/FileCheck.cpp	2015-11-17 14:00:52.000000000 -0500
++++ utils/FileCheck/FileCheck.cpp	2016-05-08 23:19:20.580431920 -0400
+@@ -40,7 +40,7 @@
+ 
+ static cl::opt<std::string>
+ InputFilename("input-file", cl::desc("File to check (defaults to stdin)"),
+-              cl::init("-"), cl::value_desc("filename"));
++              cl::init(std::string("-")), cl::value_desc("filename"));
+ 
+ static cl::list<std::string>
+ CheckPrefixes("check-prefix",
--- a/components/llvm/patches/020-21874221-clang-llvm-sparc-assembler.patch	Thu Jul 28 16:15:45 2016 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,1274 +0,0 @@
-# - https://llvm.org/bugs/show_bug.cgi?id=22623
-# - 22346218 - LLVM's assembler printer on SPARC needs a lot of work
-# - 21874221 - clang C++ does not properly initialize the C++
-# Standard Library's iostreams
-# - 22582382 - Sun ld .init_array/.fini_array handling is incompatible
-# with the GNU Toolchain
-# - 22065707 - LLVM SPARC assembler generator emits wrong ELF Section flags
-# For upstream - maybe.
---- include/llvm/MC/MCStreamer.h	2014-12-05 18:14:41.000000000 -0800
-+++ include/llvm/MC/MCStreamer.h	2015-12-09 15:14:25.413937273 -0800
-@@ -478,6 +478,13 @@
-   ///
-   virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value);
- 
-+  /// EmitELFSize - Emit an ELF .size directive.
-+  ///
-+  /// This corresponds to an assembler statement such as:
-+  ///  .size symbol, expression, but without a temp .label.
-+  ///
-+  virtual void EmitELFSize(StringRef Name);
-+
-   /// \brief Emit a Linker Optimization Hint (LOH) directive.
-   /// \param Args - Arguments of the LOH.
-   virtual void EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) {}
---- include/llvm/MC/MCSymbol.h	2014-12-24 02:27:50.000000000 -0800
-+++ include/llvm/MC/MCSymbol.h	2015-12-09 14:05:18.864224028 -0800
-@@ -51,23 +51,25 @@
-     /// 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;
-+    bool IsTemporary;
- 
-     /// \brief True if this symbol can be redefined.
--    unsigned IsRedefinable : 1;
-+    bool IsRedefinable;
- 
-     /// IsUsed - True if this symbol has been used.
--    mutable unsigned IsUsed : 1;
-+    mutable bool IsUsed;
- 
--  private:  // MCContext creates and uniques these.
-+  protected:  // MCContext creates and uniques these.
-     friend class MCExpr;
-     friend class MCContext;
-+
-     MCSymbol(StringRef name, bool isTemporary)
-       : Name(name), Section(nullptr), Value(nullptr),
--        IsTemporary(isTemporary), IsRedefinable(false), IsUsed(false) {}
-+      IsTemporary(isTemporary), IsRedefinable(false), 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; }
---- lib/MC/MCAsmStreamer.cpp	2015-01-14 03:23:27.000000000 -0800
-+++ lib/MC/MCAsmStreamer.cpp	2015-12-09 15:14:32.728543403 -0800
-@@ -40,17 +40,18 @@
- protected:
-   formatted_raw_ostream &OS;
-   const MCAsmInfo *MAI;
-+
- private:
-   std::unique_ptr<MCInstPrinter> InstPrinter;
-   std::unique_ptr<MCCodeEmitter> Emitter;
-   std::unique_ptr<MCAsmBackend> AsmBackend;
- 
--  SmallString<128> CommentToEmit;
-+  SmallString<256> CommentToEmit;
-   raw_svector_ostream CommentStream;
- 
--  unsigned IsVerboseAsm : 1;
--  unsigned ShowInst : 1;
--  unsigned UseDwarfDirectory : 1;
-+  bool IsVerboseAsm;
-+  bool ShowInst;
-+  bool UseDwarfDirectory;
- 
-   void EmitRegisterName(int64_t Register);
-   void EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) override;
-@@ -61,10 +62,10 @@
-                 bool isVerboseAsm, bool useDwarfDirectory,
-                 MCInstPrinter *printer, MCCodeEmitter *emitter,
-                 MCAsmBackend *asmbackend, bool showInst)
--      : MCStreamer(Context), OS(os), MAI(Context.getAsmInfo()),
--        InstPrinter(printer), Emitter(emitter), AsmBackend(asmbackend),
--        CommentStream(CommentToEmit), IsVerboseAsm(isVerboseAsm),
--        ShowInst(showInst), UseDwarfDirectory(useDwarfDirectory) {
-+    : MCStreamer(Context), OS(os), MAI(Context.getAsmInfo()),
-+    InstPrinter(printer), Emitter(emitter), AsmBackend(asmbackend),
-+    CommentStream(CommentToEmit), IsVerboseAsm(isVerboseAsm),
-+    ShowInst(showInst), UseDwarfDirectory(useDwarfDirectory) {
-     if (InstPrinter && IsVerboseAsm)
-       InstPrinter->setCommentStream(CommentStream);
-   }
-@@ -75,8 +76,10 @@
-       OS << '\n';
-       return;
-     }
-+
-     EmitCommentsAndEOL();
-   }
-+
-   void EmitCommentsAndEOL();
- 
-   /// isVerboseAsm - Return true if this streamer supports verbose assembly at
-@@ -139,6 +142,7 @@
-   void EmitCOFFSectionIndex(MCSymbol const *Symbol) override;
-   void EmitCOFFSecRel32(MCSymbol const *Symbol) override;
-   void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) override;
-+  void EmitELFSize(StringRef Name) override;
-   void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
-                         unsigned ByteAlignment) override;
- 
-@@ -501,6 +505,11 @@
-   OS << "\t.size\t" << *Symbol << ", " << *Value << '\n';
- }
- 
-+void MCAsmStreamer::EmitELFSize(StringRef Name) {
-+  assert(MAI->hasDotTypeDotSizeDirective());
-+  OS << "\t.size\t" << Name << ", .-" << Name << '\n';
-+}
-+
- void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
-                                      unsigned ByteAlignment) {
-   // Common symbols do not belong to any actual section.
-@@ -843,7 +852,7 @@
-   if (NumFiles == Table.getMCDwarfFiles().size())
-     return FileNo;
- 
--  SmallString<128> FullPathName;
-+  SmallString<PATH_MAX> FullPathName;
- 
-   if (!UseDwarfDirectory && !Directory.empty()) {
-     if (sys::path::is_absolute(Filename))
---- lib/MC/MCSectionELF.cpp	2014-10-09 14:23:39.000000000 -0700
-+++ lib/MC/MCSectionELF.cpp	2016-01-21 10:12:17.006210825 -0800
-@@ -59,8 +59,10 @@
-                                         raw_ostream &OS,
-                                         const MCExpr *Subsection) const {
- 
-+  StringRef SectionName = getSectionName();
-+
-   if (ShouldOmitSectionDirective(SectionName, MAI)) {
--    OS << '\t' << getSectionName();
-+    OS << '\t' << SectionName;
-     if (Subsection)
-       OS << '\t' << *Subsection;
-     OS << '\n';
-@@ -68,35 +70,20 @@
-   }
- 
-   OS << "\t.section\t";
--  printName(OS, getSectionName());
--
--  // Handle the weird solaris syntax if desired.
--  if (MAI.usesSunStyleELFSectionSwitchSyntax() &&
--      !(Flags & ELF::SHF_MERGE)) {
--    if (Flags & ELF::SHF_ALLOC)
--      OS << ",#alloc";
--    if (Flags & ELF::SHF_EXECINSTR)
--      OS << ",#execinstr";
--    if (Flags & ELF::SHF_WRITE)
--      OS << ",#write";
--    if (Flags & ELF::SHF_EXCLUDE)
--      OS << ",#exclude";
--    if (Flags & ELF::SHF_TLS)
--      OS << ",#tls";
--    OS << '\n';
--    return;
--  }
-+  printName(OS, SectionName);
- 
-   OS << ",\"";
-   if (Flags & ELF::SHF_ALLOC)
-     OS << 'a';
-   if (Flags & ELF::SHF_EXCLUDE)
-     OS << 'e';
--  if (Flags & ELF::SHF_EXECINSTR)
-+  if ((Flags & ELF::SHF_EXECINSTR) && (Type != ELF::SHT_INIT_ARRAY) &&
-+      (Type != ELF::SHT_FINI_ARRAY) && (Type != ELF::SHT_PREINIT_ARRAY))
-     OS << 'x';
-   if (Flags & ELF::SHF_GROUP)
-     OS << 'G';
--  if (Flags & ELF::SHF_WRITE)
-+  if ((Flags & ELF::SHF_WRITE) || (Type == ELF::SHT_INIT_ARRAY) ||
-+      (Type == ELF::SHT_FINI_ARRAY) || (Type == ELF::SHT_PREINIT_ARRAY))
-     OS << 'w';
-   if (Flags & ELF::SHF_MERGE)
-     OS << 'M';
-@@ -144,6 +131,7 @@
-     printName(OS, Group->getName());
-     OS << ",comdat";
-   }
-+
-   OS << '\n';
- 
-   if (Subsection)
---- lib/MC/MCStreamer.cpp	2014-11-03 04:19:03.000000000 -0800
-+++ lib/MC/MCStreamer.cpp	2015-12-09 15:15:14.428496845 -0800
-@@ -636,6 +636,7 @@
- void MCStreamer::EmitCOFFSymbolStorageClass(int StorageClass) {}
- void MCStreamer::EmitCOFFSymbolType(int Type) {}
- void MCStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
-+void MCStreamer::EmitELFSize(StringRef Name) {}
- void MCStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
-                                        unsigned ByteAlignment) {}
- void MCStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
---- tools/clang/lib/CodeGen/CGBlocks.cpp	2015-10-05 11:01:32.352334965 -0700
-+++ tools/clang/lib/CodeGen/CGBlocks.cpp	2015-12-07 15:24:59.295683990 -0800
-@@ -1248,8 +1248,8 @@
- 
-         DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointerDbgLoc,
-                                               Builder, blockInfo,
--                                              entry_ptr == entry->end()
--                                              ? nullptr : entry_ptr);
-+                                              entry_ptr == entry->end() ?
-+                                              nullptr : &*entry_ptr);
-       }
-     }
-     // Recover location if it was changed in the above loop.
---- tools/clang/lib/CodeGen/CGCall.cpp	2015-10-05 11:01:32.348582888 -0700
-+++ tools/clang/lib/CodeGen/CGCall.cpp	2015-12-07 15:26:25.691201743 -0800
-@@ -2230,7 +2230,7 @@
-     if (RetAI.getInAllocaSRet()) {
-       llvm::Function::arg_iterator EI = CurFn->arg_end();
-       --EI;
--      llvm::Value *ArgStruct = EI;
-+      llvm::Value *ArgStruct = &*EI;
-       llvm::Value *SRet =
-           Builder.CreateStructGEP(ArgStruct, RetAI.getInAllocaFieldIndex());
-       RV = Builder.CreateLoad(SRet, "sret");
-@@ -2246,7 +2246,7 @@
-       ComplexPairTy RT =
-         EmitLoadOfComplex(MakeNaturalAlignAddrLValue(ReturnValue, RetTy),
-                           EndLoc);
--      EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(AI, RetTy),
-+      EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(&*AI, RetTy),
-                          /*isInit*/ true);
-       break;
-     }
-@@ -2255,7 +2255,7 @@
-       break;
-     case TEK_Scalar:
-       EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
--                        MakeNaturalAlignAddrLValue(AI, RetTy),
-+                        MakeNaturalAlignAddrLValue(&*AI, RetTy),
-                         /*isInit*/ true);
-       break;
-     }
---- tools/clang/lib/CodeGen/CGDeclCXX.cpp	2015-10-05 11:01:32.000000000 -0700
-+++ tools/clang/lib/CodeGen/CGDeclCXX.cpp	2016-02-01 09:42:57.409779098 -0800
-@@ -23,6 +23,8 @@
- using namespace clang;
- using namespace CodeGen;
- 
-+static unsigned InitPriority = 128;
-+
- static void EmitDeclInit(CodeGenFunction &CGF, const VarDecl &D,
-                          llvm::Constant *DeclPtr) {
-   assert(D.hasGlobalStorage() && "VarDecl must have global storage!");
-@@ -137,9 +139,9 @@
-                                                bool PerformInit) {
- 
-   const Expr *Init = D.getInit();
--  QualType T = D.getType();
-+  QualType QT = D.getType();
- 
--  if (!T->isReferenceType()) {
-+  if (!QT->isReferenceType()) {
-     if (getLangOpts().OpenMP && D.hasAttr<OMPThreadPrivateDeclAttr>())
-       (void)CGM.getOpenMPRuntime().EmitOMPThreadPrivateVarDefinition(
-           &D, DeclPtr, D.getAttr<OMPThreadPrivateDeclAttr>()->getLocation(),
-@@ -157,7 +159,7 @@
-          "destruction for reference");
-   unsigned Alignment = getContext().getDeclAlign(&D).getQuantity();
-   RValue RV = EmitReferenceBindingToExpr(Init);
--  EmitStoreOfScalar(RV.getScalarVal(), DeclPtr, false, Alignment, T);
-+  EmitStoreOfScalar(RV.getScalarVal(), DeclPtr, false, Alignment, QT);
- }
- 
- /// Create a stub function, suitable for being passed to atexit,
-@@ -166,22 +168,25 @@
-                                                   llvm::Constant *dtor,
-                                                   llvm::Constant *addr) {
-   // Get the destructor function type, void(*)(void).
--  llvm::FunctionType *ty = llvm::FunctionType::get(CGM.VoidTy, false);
--  SmallString<256> FnName;
-+  llvm::FunctionType *FTy = llvm::FunctionType::get(CGM.VoidTy, false);
-+  SmallString<512> FnName;
-   {
-     llvm::raw_svector_ostream Out(FnName);
-     CGM.getCXXABI().getMangleContext().mangleDynamicAtExitDestructor(&VD, Out);
-   }
--  llvm::Function *fn = CGM.CreateGlobalInitOrDestructFunction(ty, FnName.str(),
--                                                              VD.getLocation());
-+
-+  llvm::Function *Fn =
-+    CGM.CreateGlobalInitOrDestructFunction(FTy, FnName.str(),
-+                                           VD.getLocation());
- 
-   CodeGenFunction CGF(CGM);
- 
--  CGF.StartFunction(&VD, CGM.getContext().VoidTy, fn,
--                    CGM.getTypes().arrangeNullaryFunction(), FunctionArgList());
-+  CGF.StartFunction(&VD, CGM.getContext().VoidTy, Fn,
-+                    CGM.getTypes().arrangeNullaryFunction(),
-+                    FunctionArgList());
- 
-   llvm::CallInst *call = CGF.Builder.CreateCall(dtor, addr);
-- 
-+
-  // Make sure the call and the callee agree on calling convention.
-   if (llvm::Function *dtorFn =
-         dyn_cast<llvm::Function>(dtor->stripPointerCasts()))
-@@ -189,7 +194,7 @@
- 
-   CGF.FinishFunction();
- 
--  return fn;
-+  return Fn;
- }
- 
- /// Register a global destructor using the C atexit runtime function.
-@@ -203,12 +208,12 @@
-   llvm::FunctionType *atexitTy =
-     llvm::FunctionType::get(IntTy, dtorStub->getType(), false);
- 
--  llvm::Constant *atexit =
-+  llvm::Constant *atExit =
-     CGM.CreateRuntimeFunction(atexitTy, "atexit");
--  if (llvm::Function *atexitFn = dyn_cast<llvm::Function>(atexit))
-+  if (llvm::Function *atexitFn = dyn_cast<llvm::Function>(atExit))
-     atexitFn->setDoesNotThrow();
- 
--  EmitNounwindRuntimeCall(atexit, dtorStub);
-+  EmitNounwindRuntimeCall(atExit, dtorStub);
- }
- 
- void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D,
-@@ -225,15 +230,29 @@
-   CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr, PerformInit);
- }
- 
--llvm::Function *CodeGenModule::CreateGlobalInitOrDestructFunction(
--    llvm::FunctionType *FTy, const Twine &Name, SourceLocation Loc, bool TLS) {
-+llvm::Function*
-+CodeGenModule::CreateGlobalInitOrDestructFunction(llvm::FunctionType *FTy,
-+                                                  const Twine &Name,
-+                                                  SourceLocation Loc,
-+                                                  bool TLS) {
-   llvm::Function *Fn =
-     llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
-                            Name, &getModule());
-+
-+  // Set the section if needed.
-   if (!getLangOpts().AppleKext && !TLS) {
--    // Set the section if needed.
--    if (const char *Section = getTarget().getStaticInitSectionSpecifier())
--      Fn->setSection(Section);
-+    if (const char *Section = getTarget().getStaticInitSectionSpecifier()) {
-+      if (getTriple().getOS() == llvm::Triple::Solaris) {
-+        std::string FNm = Fn->getName().str();
-+        if ((FNm.find("_GLOBAL__sub_I_") != std::string::npos) &&
-+            !CodeGenOpts.UseInitArray)
-+          Fn->setSection(Section);
-+        else
-+          Fn->setSection(".text");
-+      } else {
-+        Fn->setSection(Section);
-+      }
-+    }
-   }
- 
-   Fn->setCallingConv(getRuntimeCC());
-@@ -241,13 +260,16 @@
-   if (!getLangOpts().Exceptions)
-     Fn->setDoesNotThrow();
- 
--  if (!isInSanitizerBlacklist(Fn, Loc)) {
--    if (getLangOpts().Sanitize.has(SanitizerKind::Address))
--      Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
--    if (getLangOpts().Sanitize.has(SanitizerKind::Thread))
--      Fn->addFnAttr(llvm::Attribute::SanitizeThread);
--    if (getLangOpts().Sanitize.has(SanitizerKind::Memory))
--      Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
-+  // Solaris does not yet support the Sanitizer Libraries.
-+  if (getTriple().getOS() != llvm::Triple::Solaris) {
-+    if (!isInSanitizerBlacklist(Fn, Loc)) {
-+      if (getLangOpts().Sanitize.has(SanitizerKind::Address))
-+        Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
-+      if (getLangOpts().Sanitize.has(SanitizerKind::Thread))
-+        Fn->addFnAttr(llvm::Attribute::SanitizeThread);
-+      if (getLangOpts().Sanitize.has(SanitizerKind::Memory))
-+        Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
-+    }
-   }
- 
-   return Fn;
-@@ -260,9 +282,21 @@
-                                           llvm::GlobalVariable *GV,
-                                           llvm::Function *InitFunc,
-                                           InitSegAttr *ISA) {
--  llvm::GlobalVariable *PtrArray = new llvm::GlobalVariable(
--      TheModule, InitFunc->getType(), /*isConstant=*/true,
--      llvm::GlobalValue::PrivateLinkage, InitFunc, "__cxx_init_fn_ptr");
-+  std::string GVN("__cxx_init_fn_ptr");
-+  if (getTriple().getOS() == llvm::Triple::Solaris) {
-+    GVN += "_";
-+    GVN += std::to_string(InitPriority++);
-+  }
-+
-+  llvm::GlobalVariable *PtrArray = nullptr;
-+
-+  PtrArray = new llvm::GlobalVariable(TheModule, InitFunc->getType(),
-+                                      /*isConstant=*/ true,
-+                                      llvm::GlobalValue::PrivateLinkage,
-+                                      InitFunc, GVN);
-+
-+  assert(PtrArray && "Invalid Function Pointer Array!");
-+
-   PtrArray->setSection(ISA->getSection());
-   addUsedGlobal(PtrArray);
- 
-@@ -283,22 +317,76 @@
- CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
-                                             llvm::GlobalVariable *Addr,
-                                             bool PerformInit) {
--  llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
-+  llvm::FunctionType *FTy = nullptr;
-+  std::vector<llvm::Type*> ArgsVec;
-+
-+  if (getTriple().getOS() == llvm::Triple::Solaris) {
-+    ArgsVec.push_back(IntTy);
-+    ArgsVec.push_back(IntTy);
-+    FTy = llvm::FunctionType::get(VoidTy, ArgsVec, false);
-+  } else {
-+    FTy = llvm::FunctionType::get(VoidTy, false);
-+  }
-+
-   SmallString<256> FnName;
-   {
-     llvm::raw_svector_ostream Out(FnName);
--    getCXXABI().getMangleContext().mangleDynamicInitializer(D, Out);
-+    if (getTriple().getOS() == llvm::Triple::Solaris)
-+      getCXXABI().getMangleContext().mangleGCCDynamicInitializer(D, Out);
-+    else
-+      getCXXABI().getMangleContext().mangleDynamicInitializer(D, Out);
-   }
- 
-   // Create a variable initialization function.
-   llvm::Function *Fn =
-       CreateGlobalInitOrDestructFunction(FTy, FnName.str(), D->getLocation());
-+  Fn->setDoesNotThrow();
- 
-   auto *ISA = D->getAttr<InitSegAttr>();
--  CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr,
--                                                          PerformInit);
- 
--  llvm::GlobalVariable *COMDATKey =
-+  if (getTriple().getOS() == llvm::Triple::Solaris) {
-+    ASTContext &Ctx = getContext();
-+    auto *IPA = D->getAttr<InitPriorityAttr>();
-+    if (!IPA) {
-+      IPA = InitPriorityAttr::CreateImplicit(Ctx, /* InitPriority */ 65535);
-+      VarDecl *DD = const_cast<VarDecl*>(D);
-+      DD->addAttr(IPA);
-+    }
-+
-+    if (!ISA && CodeGenOpts.UseInitArray) {
-+      ISA = InitSegAttr::CreateImplicit(Ctx, PerformInit ?
-+                                        StringRef(".init_array") :
-+                                        StringRef(".fini_array"));
-+      VarDecl *DD = const_cast<VarDecl*>(D);
-+      DD->addAttr(ISA);
-+    }
-+  }
-+
-+  FunctionArgList ArgList;
-+  ASTContext &Ctx = getContext();
-+  // We cannot allocate these dynamically because of a very ill-conceived
-+  // operator new overload in DeclBase.h.
-+  ImplicitParamDecl IAFirst(Ctx, /*DC=*/ nullptr, D->getLocation(),
-+                            /*Id=*/ nullptr, Ctx.UnsignedIntTy);
-+  ImplicitParamDecl IASecond(Ctx, /*DC=*/ nullptr, D->getLocation(),
-+                             /*Id=*/ nullptr, Ctx.UnsignedIntTy);
-+
-+  if (getTriple().getOS() == llvm::Triple::Solaris) {
-+    // Add Parameters to the Function ArgumentList on Solaris
-+    // for compatibility with the GCC C++ Runtime.
-+    ArgList.push_back(&IAFirst);
-+    ArgList.push_back(&IASecond);
-+  }
-+
-+  CodeGenFunction CGF(*this);
-+  CGF.GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr, PerformInit, ArgList);
-+
-+  llvm::GlobalVariable *COMDATKey;
-+
-+  if (getTriple().getOS() == llvm::Triple::Solaris)
-+    COMDATKey = D->isExternallyVisible() ? Addr : nullptr;
-+  else
-+    COMDATKey =
-       supportsCOMDAT() && D->isExternallyVisible() ? Addr : nullptr;
- 
-   if (D->getTLSKind()) {
-@@ -370,7 +458,6 @@
- 
-   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
- 
--
-   // Create our global initialization function.
-   if (!PrioritizedCXXGlobalInits.empty()) {
-     SmallVector<llvm::Function *, 8> LocalCXXGlobalInits;
-@@ -391,9 +478,10 @@
-       // sure the function names are also ordered as priorities.
-       std::string PrioritySuffix = llvm::utostr(Priority);
-       // Priority is always <= 65535 (enforced by sema).
--      PrioritySuffix = std::string(6-PrioritySuffix.size(), '0')+PrioritySuffix;
--      llvm::Function *Fn = CreateGlobalInitOrDestructFunction(
--          FTy, "_GLOBAL__I_" + PrioritySuffix);
-+      PrioritySuffix =
-+        std::string(6 - PrioritySuffix.size(), '0') + PrioritySuffix;
-+      llvm::Function *Fn =
-+        CreateGlobalInitOrDestructFunction(FTy, "_GLOBAL__I_" + PrioritySuffix);
- 
-       for (; I < PrioE; ++I)
-         LocalCXXGlobalInits.push_back(I->second);
-@@ -403,7 +491,7 @@
-     }
-   }
- 
--  SmallString<128> FileName;
-+  SmallString<PATH_MAX> FileName;
-   SourceManager &SM = Context.getSourceManager();
-   if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
-     // Include the filename in the symbol name. Including "sub_" matches gcc and
-@@ -417,14 +505,15 @@
-   for (size_t i = 0; i < FileName.size(); ++i) {
-     // Replace everything that's not [a-zA-Z0-9._] with a _. This set happens
-     // to be the set of C preprocessing numbers.
--    if (!isPreprocessingNumberBody(FileName[i]))
-+    if (!isPreprocessingNumberBody(FileName[i]) || (FileName[i] == '.'))
-       FileName[i] = '_';
-   }
- 
-   llvm::Function *Fn = CreateGlobalInitOrDestructFunction(
-       FTy, llvm::Twine("_GLOBAL__sub_I_", FileName));
- 
--  CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, CXXGlobalInits);
-+  CodeGenFunction CGF(*this);
-+  CGF.GenerateCXXGlobalInitFunc(Fn, CXXGlobalInits);
-   AddGlobalCtor(Fn);
- 
-   CXXGlobalInits.clear();
-@@ -445,28 +534,43 @@
- }
- 
- /// Emit the code necessary to initialize the given global variable.
--void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
--                                                       const VarDecl *D,
--                                                 llvm::GlobalVariable *Addr,
--                                                       bool PerformInit) {
-+void
-+CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
-+                                                  const VarDecl *D,
-+                                                  llvm::GlobalVariable *Addr,
-+                                                  bool PerformInit,
-+                                                  FunctionArgList ArgList) {
-   // Check if we need to emit debug info for variable initializer.
-   if (D->hasAttr<NoDebugAttr>())
-     DebugInfo = nullptr; // disable debug info indefinitely for this function
- 
-   CurEHLocation = D->getLocStart();
-+  ASTContext &Ctx = getContext();
- 
--  StartFunction(GlobalDecl(D), getContext().VoidTy, Fn,
--                getTypes().arrangeNullaryFunction(),
--                FunctionArgList(), D->getLocation(),
-+  FunctionType::ExtInfo ExtInfo;
-+  const CGFunctionInfo &FuncInfo =
-+    getTypes().arrangeFreeFunctionDeclaration(Ctx.VoidTy, ArgList,
-+                                              ExtInfo, /*IsVariadic=*/ false);
-+  GlobalDecl GD(D);
-+
-+  StartFunction(GD, Ctx.VoidTy, Fn, FuncInfo, ArgList, D->getLocation(),
-                 D->getInit()->getExprLoc());
- 
--  // Use guarded initialization if the global variable is weak. This
--  // occurs for, e.g., instantiated static data members and
--  // definitions explicitly marked weak.
--  if (Addr->hasWeakLinkage() || Addr->hasLinkOnceLinkage()) {
--    EmitCXXGuardedInit(*D, Addr, PerformInit);
-+  if (CGM.getTriple().getOS() == llvm::Triple::Solaris) {
-+    if (Addr->hasWeakLinkage()) {
-+      EmitCXXGuardedInit(*D, Addr, PerformInit);
-+    } else {
-+      EmitCXXGlobalVarDeclInit(*D, Addr, PerformInit);
-+    }
-   } else {
--    EmitCXXGlobalVarDeclInit(*D, Addr, PerformInit);
-+    // Use guarded initialization if the global variable is weak. This
-+    // occurs for, e.g., instantiated static data members and
-+    // definitions explicitly marked weak.
-+    if (Addr->hasWeakLinkage() || Addr->hasLinkOnceLinkage()) {
-+      EmitCXXGuardedInit(*D, Addr, PerformInit);
-+    } else {
-+      EmitCXXGlobalVarDeclInit(*D, Addr, PerformInit);
-+    }
-   }
- 
-   FinishFunction();
-@@ -476,10 +580,21 @@
- CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
-                                            ArrayRef<llvm::Function *> Decls,
-                                            llvm::GlobalVariable *Guard) {
-+  llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
-+  ASTContext &Ctx = getContext();
-+  llvm::LLVMContext &LLVMCtx = CGM.getLLVMContext();
-+
-   {
-     ApplyDebugLocation NL(*this);
--    StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
--                  getTypes().arrangeNullaryFunction(), FunctionArgList());
-+
-+    FunctionArgList ArgList;
-+    FunctionType::ExtInfo ExtInfo;
-+    const CGFunctionInfo &FuncInfo =
-+      getTypes().arrangeFreeFunctionDeclaration(Ctx.VoidTy, ArgList,
-+                                                ExtInfo,
-+                                                /*IsVariadic=*/ false);
-+    StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, FuncInfo, ArgList);
-+
-     // Emit an artificial location for this function.
-     ArtificialLocation AL(*this);
- 
-@@ -509,9 +624,27 @@
-       EmitObjCAutoreleasePoolCleanup(token);
-     }
- 
--    for (unsigned i = 0, e = Decls.size(); i != e; ++i)
--      if (Decls[i])
--        EmitRuntimeCall(Decls[i]);
-+    for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
-+      if (llvm::Function *FV = Decls[i]) {
-+        if (CGM.getTriple().getOS() == llvm::Triple::Solaris) {
-+          llvm::Value *Values[2] = { nullptr, nullptr };
-+          Values[0] =
-+            llvm::ConstantInt::get(llvm::Type::getInt32Ty(LLVMCtx), 1);
-+          Values[1] =
-+            llvm::ConstantInt::get(llvm::Type::getInt32Ty(LLVMCtx), 65535);
-+          ArrayRef<llvm::Value*> ArgValues = llvm::makeArrayRef(Values);
-+          llvm::CallInst *CI = EmitRuntimeCall(FV, ArgValues);
-+#ifndef NDEBUG
-+          llvm::Function *CIF = CI->getCalledFunction();
-+          assert (CIF && "Invalid function returned in CallInst!");
-+#else
-+          (void) CI;
-+#endif
-+        } else {
-+          EmitRuntimeCall(Decls[i]);
-+        }
-+      }
-+    }
- 
-     Scope.ForceCleanup();
- 
-@@ -569,8 +702,8 @@
-   StartFunction(VD, getContext().VoidTy, fn, FI, args);
- 
-   emitDestroy(addr, type, destroyer, useEHCleanupForArray);
--  
-+
-   FinishFunction();
--  
-+
-   return fn;
- }
---- tools/clang/lib/CodeGen/CGExprScalar.cpp	2015-10-05 11:01:32.351864633 -0700
-+++ tools/clang/lib/CodeGen/CGExprScalar.cpp	2015-12-07 16:39:38.372167280 -0800
-@@ -2319,9 +2319,9 @@
- 
-   // Branch in case of overflow.
-   llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
--  llvm::Function::iterator insertPt = initialBB;
-+  llvm::Function::iterator insertPt = initialBB->getIterator();
-   llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn,
--                                                      std::next(insertPt));
-+                                                      &*std::next(insertPt));
-   llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
- 
-   Builder.CreateCondBr(overflow, overflowBB, continueBB);
---- tools/clang/lib/CodeGen/CGExpr.cpp	2015-10-05 11:01:32.356618553 -0700
-+++ tools/clang/lib/CodeGen/CGExpr.cpp	2015-12-07 16:36:56.944848497 -0800
-@@ -64,7 +64,7 @@
-                                      llvm::Value *Init) {
-   auto *Store = new llvm::StoreInst(Init, Var);
-   llvm::BasicBlock *Block = AllocaInsertPt->getParent();
--  Block->getInstList().insertAfter(&*AllocaInsertPt, Store);
-+  Block->getInstList().insertAfter(AllocaInsertPt->getIterator(), Store);
- }
- 
- llvm::AllocaInst *CodeGenFunction::CreateIRTemp(QualType Ty,
---- tools/clang/lib/CodeGen/CGStmt.cpp	2015-10-05 11:01:32.627209320 -0700
-+++ tools/clang/lib/CodeGen/CGStmt.cpp	2015-12-07 16:52:55.040873133 -0800
-@@ -329,7 +329,7 @@
-     return;
- 
-   // Can only simplify empty blocks.
--  if (BI != BB->begin())
-+  if (BI->getIterator() != BB->begin())
-     return;
- 
-   BB->replaceAllUsesWith(BI->getSuccessor(0));
-@@ -351,7 +351,7 @@
-   // Place the block after the current block, if possible, or else at
-   // the end of the function.
-   if (CurBB && CurBB->getParent())
--    CurFn->getBasicBlockList().insertAfter(CurBB, BB);
-+    CurFn->getBasicBlockList().insertAfter(CurBB->getIterator(), BB);
-   else
-     CurFn->getBasicBlockList().push_back(BB);
-   Builder.SetInsertPoint(BB);
-@@ -378,7 +378,8 @@
-   bool inserted = false;
-   for (llvm::User *u : block->users()) {
-     if (llvm::Instruction *insn = dyn_cast<llvm::Instruction>(u)) {
--      CurFn->getBasicBlockList().insertAfter(insn->getParent(), block);
-+      CurFn->getBasicBlockList().insertAfter(insn->getParent()->getIterator(),
-+                                             block);
-       inserted = true;
-       break;
-     }
---- tools/clang/lib/CodeGen/CGVTables.cpp	2015-10-05 11:01:32.353244828 -0700
-+++ tools/clang/lib/CodeGen/CGVTables.cpp	2015-12-07 17:11:22.736212205 -0800
-@@ -158,12 +158,16 @@
-   // Find the first store of "this", which will be to the alloca associated
-   // with "this".
-   llvm::Value *ThisPtr = &*AI;
--  llvm::BasicBlock *EntryBB = Fn->begin();
-+  llvm::BasicBlock *EntryBB = &Fn->front();
-   llvm::Instruction *ThisStore =
--      std::find_if(EntryBB->begin(), EntryBB->end(), [&](llvm::Instruction &I) {
--    return isa<llvm::StoreInst>(I) && I.getOperand(0) == ThisPtr;
--  });
-+      &*std::find_if(EntryBB->begin(), EntryBB->end(), [&](llvm::Instruction &I)
-+                     {
-+                     return isa<llvm::StoreInst>(I) &&
-+                     I.getOperand(0) == ThisPtr;
-+                     });
-+
-   assert(ThisStore && "Store of this should be in entry block?");
-+
-   // Adjust "this", if necessary.
-   Builder.SetInsertPoint(ThisStore);
-   llvm::Value *AdjustedThisPtr =
---- tools/clang/lib/CodeGen/CodeGenFunction.cpp	2015-10-05 11:01:32.357401838 -0700
-+++ tools/clang/lib/CodeGen/CodeGenFunction.cpp	2015-12-07 17:13:22.309802713 -0800
-@@ -672,14 +672,14 @@
-     auto AI = CurFn->arg_begin();
-     if (CurFnInfo->getReturnInfo().isSRetAfterThis())
-       ++AI;
--    ReturnValue = AI;
-+    ReturnValue = &*AI;
-   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
-              !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
-     // Load the sret pointer from the argument struct and return into that.
-     unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
-     llvm::Function::arg_iterator EI = CurFn->arg_end();
-     --EI;
--    llvm::Value *Addr = Builder.CreateStructGEP(EI, Idx);
-+    llvm::Value *Addr = Builder.CreateStructGEP(&*EI, Idx);
-     ReturnValue = Builder.CreateLoad(Addr, "agg.result");
-   } else {
-     ReturnValue = CreateIRTemp(RetTy, "retval");
---- tools/clang/lib/CodeGen/CodeGenFunction.h	2015-10-05 11:01:32.347172460 -0700
-+++ tools/clang/lib/CodeGen/CodeGenFunction.h	2015-10-14 18:25:20.000000000 -0700
-@@ -2572,10 +2572,11 @@
-   void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
-                                         const VarDecl *D,
-                                         llvm::GlobalVariable *Addr,
--                                        bool PerformInit);
-+                                        bool PerformInit,
-+                                        FunctionArgList ArgList);
- 
-   void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest);
--  
-+
-   void EmitSynthesizedCXXCopyCtor(llvm::Value *Dest, llvm::Value *Src,
-                                   const Expr *Exp);
- 
---- tools/clang/lib/CodeGen/CodeGenModule.cpp	2015-10-05 11:01:32.354174460 -0700
-+++ tools/clang/lib/CodeGen/CodeGenModule.cpp	2016-02-01 09:44:08.493171103 -0800
-@@ -228,7 +228,8 @@
-     OldF->replaceAllUsesWith(Replacement);
-     if (NewF) {
-       NewF->removeFromParent();
--      OldF->getParent()->getFunctionList().insertAfter(OldF, NewF);
-+      OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
-+                                                       NewF);
-     }
-     OldF->eraseFromParent();
-   }
-@@ -272,8 +273,16 @@
-       Error = true;
-       Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
-     } else if (GV->isDeclaration()) {
--      Error = true;
--      Diags.Report(AA->getLocation(), diag::err_alias_to_undefined);
-+      clang::Linkage L = D->getFormalLinkage();
-+      const auto *FD = cast<FunctionDecl>(D);
-+
-+      if (!FD && ((L != clang::ExternalLinkage) &&
-+                  (L != clang::UniqueExternalLinkage) &&
-+                  (L != clang::InternalLinkage) &&
-+                  (L != clang::VisibleNoLinkage))) {
-+        Error = true;
-+        Diags.Report(AA->getLocation(), diag::err_alias_to_undefined);
-+      }
-     }
- 
-     llvm::Constant *Aliasee = Alias->getAliasee();
-@@ -1310,10 +1319,7 @@
- 
- void CodeGenModule::EmitGlobal(GlobalDecl GD) {
-   const auto *Global = cast<ValueDecl>(GD.getDecl());
--
--  // Weak references don't produce any output by themselves.
--  if (Global->hasAttr<WeakRefAttr>())
--    return;
-+  assert(Global && "Cast to ValueDecl yields nullptr!");
- 
-   // If this is an alias definition (which otherwise looks like a declaration)
-   // emit it now.
-@@ -1485,16 +1491,11 @@
- void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
-   const auto *D = cast<ValueDecl>(GD.getDecl());
- 
--  PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 
-+  PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
-                                  Context.getSourceManager(),
-                                  "Generating code for declaration");
--  
--  if (isa<FunctionDecl>(D)) {
--    // At -O0, don't generate IR for functions with available_externally 
--    // linkage.
--    if (!shouldEmitFunction(GD))
--      return;
- 
-+  if (isa<FunctionDecl>(D)) {
-     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
-       CompleteDIClassType(Method);
-       // Make sure to emit the definition(s) before we emit the thunks.
-@@ -1512,13 +1513,18 @@
-       return;
-     }
- 
--    return EmitGlobalFunctionDefinition(GD, GV);
-+    EmitGlobalFunctionDefinition(GD, GV);
-+    return;
-+  }
-+
-+  if (const auto *VD = dyn_cast<VarDecl>(D)) {
-+    EmitGlobalVarDefinition(VD);
-+    return;
-   }
- 
--  if (const auto *VD = dyn_cast<VarDecl>(D))
--    return EmitGlobalVarDefinition(VD);
--  
--  llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
-+  llvm::errs() << __PRETTY_FUNCTION__
-+    << ": Invalid argument to EmitGlobalDefinition()!\n";
-+  return;
- }
- 
- /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
---- tools/clang/lib/CodeGen/CodeGenModule.h	2015-10-05 11:01:32.344046428 -0700
-+++ tools/clang/lib/CodeGen/CodeGenModule.h	2015-10-20 21:11:16.000000000 -0700
-@@ -692,7 +692,8 @@
-                                     llvm::GlobalValue::LinkageTypes Linkage);
- 
-   llvm::Function *
--  CreateGlobalInitOrDestructFunction(llvm::FunctionType *ty, const Twine &name,
-+  CreateGlobalInitOrDestructFunction(llvm::FunctionType *FTy,
-+                                     const Twine &Name,
-                                      SourceLocation Loc = SourceLocation(),
-                                      bool TLS = false);
- 
---- tools/clang/lib/CodeGen/CodeGenPGO.cpp	2015-10-05 11:01:32.349650190 -0700
-+++ tools/clang/lib/CodeGen/CodeGenPGO.cpp	2015-12-08 07:11:06.067357170 -0800
-@@ -788,8 +788,10 @@
- void CodeGenPGO::emitCounterIncrement(CGBuilderTy &Builder, unsigned Counter) {
-   if (!CGM.getCodeGenOpts().ProfileInstrGenerate || !RegionCounterMap)
-     return;
--  if (!Builder.GetInsertPoint())
-+
-+  if (!Builder.GetInsertBlock())
-     return;
-+
-   auto *I8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
-   Builder.CreateCall4(CGM.getIntrinsic(llvm::Intrinsic::instrprof_increment),
-                       llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
---- tools/clang/lib/Driver/ToolChains.cpp	2016-02-01 14:47:49.483365583 -0800
-+++ tools/clang/lib/Driver/ToolChains.cpp	2016-02-01 09:12:57.596182227 -0800
-@@ -2918,6 +2918,11 @@
-   const llvm::Triple& TT = getTriple();
-   llvm::Triple::ArchType Arch = TT.getArch();
- 
-+  if (Arg *A = DriverArgs.getLastArg(options::OPT_fuse_init_array)) {
-+    CC1Args.push_back("-fuse-init-array");
-+    DriverArgs.ClaimAllArgs(options::OPT_fuse_init_array);
-+  }
-+
-   if (Arg *A = DriverArgs.getLastArg(options::OPT_mtune_EQ)) {
-     StringRef V = A->getValue();
-     if (!V.empty())
---- tools/clang/lib/Driver/ToolChains.cpp	2016-02-01 18:49:01.325382261 -0800
-+++ tools/clang/lib/Driver/ToolChains.cpp	2016-02-01 19:59:25.420298464 -0800
-@@ -3012,13 +3012,22 @@
- 
- void Solaris::findGCCMajorMinorMicro(const llvm::Triple& T) const {
-   // FIXME: Add 5.2.0 after testing the ABI.
--  static const char* const GCCMMM[] = { "4.8.2", "4.8.5", "4.9.3" };
-+  static const char* const GCCMMM[] = { "4.8.2", "4.9.3", "4.9.4" };
- 
-   const char* P;
-   std::string Path;
-   std::string TripleString = llvm::sys::getDefaultTargetTriple();
-   llvm::Triple::ArchType Arch = T.getArch();
- 
-+  // GCC4 on Solaris is multilib 32/64.
-+  // GCC5 (not supported here yet) on Solaris is multilib 64/32.
-+  if (GCCMajorMinor[0] == '4') {
-+    if (TripleString.find("x86_64") != std::string::npos)
-+      TripleString.replace(0U, 6U, std::string("i386"));
-+    else if (TripleString.find("sparcv9") != std::string::npos)
-+      TripleString.replace(0U, 7U, std::string("sparc"));
-+  }
-+
-   if (UseMediatedGCCToolChainPath) {
-     // FIXME: IMPLEMENT.
-     // Needs spec.
---- tools/clang/lib/Driver/Tools.cpp	2015-10-12 22:12:01.440488058 -0700
-+++ tools/clang/lib/Driver/Tools.cpp	2016-02-01 10:32:24.767483623 -0800
-@@ -45,6 +45,10 @@
- using namespace clang;
- using namespace llvm::opt;
- 
-+#if defined(LLVM_ON_UNIX)
-+#include <sys/utsname.h>
-+#endif
-+
- static void addAssemblerKPIC(const ArgList &Args, ArgStringList &CmdArgs) {
-   Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
-                                     options::OPT_fpic, options::OPT_fno_pic,
-@@ -4595,8 +4599,10 @@
-   // nice to enable this when doing a crashdump for modules as well.
-   if (Args.hasFlag(options::OPT_frewrite_includes,
-                    options::OPT_fno_rewrite_includes, false) ||
--      (C.isForDiagnostics() && !HaveModules))
--    CmdArgs.push_back("-frewrite-includes");
-+      (C.isForDiagnostics() && !HaveModules)) {
-+    if (getToolChain().getTriple().getOS() != llvm::Triple::Solaris)
-+      CmdArgs.push_back("-frewrite-includes");
-+  }
- 
-   // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
-   if (Arg *A = Args.getLastArg(options::OPT_traditional,
-@@ -6379,6 +6385,8 @@
- 
-   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
-                        options::OPT_Xassembler);
-+  Args.ClaimAllArgs(options::OPT_Wa_COMMA);
-+  Args.ClaimAllArgs(options::OPT_Xassembler);
- 
-   for (const auto &II : Inputs) {
-     if (II.getType() == types::TY_LLVM_IR ||
-@@ -6517,6 +6525,11 @@
-   ArgStringList CmdArgs;
- 
-   CmdArgs.push_back(Args.MakeArgString("-zignore"));
-+  CmdArgs.push_back(Args.MakeArgString("-zrelax=common"));
-+  CmdArgs.push_back(Args.MakeArgString("-zrelax=secadj"));
-+  CmdArgs.push_back(Args.MakeArgString("-zrelax=transtls"));
-+  if (D.CCCIsCXX())
-+    CmdArgs.push_back(Args.MakeArgString("-zrelax=comdat"));
- 
-   Arg *PIEArg = Args.getLastArg(options::OPT_fPIE, options::OPT_fpie);
-   if (PIEArg) {
-@@ -6527,7 +6540,7 @@
-       CmdArgs.push_back(Args.MakeArgString("-ztextwarn"));
-       CmdArgs.push_back(Args.MakeArgString("-ztype=pie"));
-       CmdArgs.push_back(Args.MakeArgString("-zaslr=enable"));
--  }
-+    }
-   }
- 
-   // Silence warning for "-g: argument not used during compilation
-@@ -6656,10 +6669,21 @@
-   if (!Args.hasArg(options::OPT_nostdlib) &&
-       !Args.hasArg(options::OPT_nostartfiles)) {
-     if (!Args.hasArg(options::OPT_shared)) {
-+      std::string UNM = "5.12";
-+
-+#if defined(LLVM_ON_UNIX) // Because Windows?
-+      struct utsname UTS;
-+      if (::uname(&UTS) == 0)
-+        UNM = UTS.version;
-+#endif
-+
-       switch (Arch) {
-       case llvm::Triple::sparc:
-       case llvm::Triple::sparcv9:
--        crt1o = GCCLibPath;
-+        if (UNM == "5.12")
-+          crt1o = LibPath;
-+        else
-+          crt1o = GCCLibPath;
-         break;
-       case llvm::Triple::x86:
-       case llvm::Triple::x86_64:
-@@ -6754,7 +6778,8 @@
-           CXAFinalize = *B + "/cxa_finalize.o";
-         }
- 
--        if (llvm::sys::fs::exists(CXAFinalize.c_str()))
-+        HasSystemCXAFinalize = llvm::sys::fs::exists(CXAFinalize.c_str());
-+        if (D.CCCIsCXX() && HasSystemCXAFinalize)
-           CmdArgs.push_back(Args.MakeArgString(CXAFinalize.c_str()));
-       }
-     }
-@@ -6784,8 +6809,10 @@
-   // Itanium C++ ABI.
-   if (D.CCCIsCXX()) {
-     if (!Args.hasArg(options::OPT_shared)) {
--      const char* zfiniarray = "-zfiniarray=__cxa_finalize";
--      CmdArgs.push_back(Args.MakeArgString(zfiniarray));
-+      if (HasSystemCXAFinalize) {
-+        const char* zfiniarray = "-zfiniarray=__cxa_finalize";
-+        CmdArgs.push_back(Args.MakeArgString(zfiniarray));
-+      }
-     }
-   }
- 
-@@ -6843,6 +6870,9 @@
- 
-   addProfileRT(TC, Args, CmdArgs);
- 
-+  Args.ClaimAllArgs(options::OPT_Wl_COMMA);
-+  Args.ClaimAllArgs(options::OPT_Xlinker);
-+
-   C.addCommand(llvm::make_unique<Command>(JA, *this,
-                                           Args.MakeArgString(Linker),
-                                           CmdArgs));
---- tools/clang/lib/Basic/Targets.cpp	2015-10-27 10:02:43.744975392 -0700
-+++ tools/clang/lib/Basic/Targets.cpp	2016-02-01 08:33:09.756656790 -0800
-@@ -537,6 +537,10 @@
-     Builder.defineMacro("__ELF__");
-     Builder.defineMacro("__svr4__");
-     Builder.defineMacro("__SVR4");
-+    Builder.defineMacro("__SunOS", "1");
-+
-+    if (Opts.CPlusPlus || Opts.CPlusPlus11 || Opts.CPlusPlus14)
-+      Builder.defineMacro("__GTHREADS", "1");
- 
-     if (Opts.C99 || Opts.CPlusPlus11) {
-       if (Opts.C99) {
-@@ -549,39 +553,51 @@
-       Builder.defineMacro("__C99FEATURES__", "1");
-     }
- 
--    if (Opts.CPlusPlus11)
--      Builder.defineMacro("__cplusplus", "201103L");
--    else if (Opts.CPlusPlus14)
--      Builder.defineMacro("__cplusplus", "201402L");
-+    if (Opts.CPlusPlus11 || Opts.CPlusPlus14) {
-+      Builder.defineMacro("__STDCPP_STRICT_POINTER_SAFETY__", "1");
-+      Builder.defineMacro("__STDCPP_THREADS__", "1");
-+    }
- 
-     if (Opts.CPlusPlus11) {
--      Builder.defineMacro("_STDC_C11", "1");
-+      Builder.defineMacro("__STDC_ISO_10646__", "201011L");
-+      Builder.defineMacro("__STDC_MB_MIGHT_NEQ_WC__", "1");
-       Builder.defineMacro("_STDC_C11_BCI", "1");
-       Builder.defineMacro("__XPG7_THREAD_MODEL__", "1");
-       Builder.defineMacro("_XPG7", "1");
-       Builder.defineMacro("_XOPEN_SOURCE", "700");
-     } else if (Opts.C11 || Opts.CPlusPlus14) {
-+      Builder.defineMacro("__STDC_HOSTED__", "1");
-       Builder.defineMacro("__STDC_VERSION__", "201112L");
-       Builder.defineMacro("_STDC_C11", "1");
-       Builder.defineMacro("_STDC_C11_BCI", "1");
-+      Builder.defineMacro("__STDC_ISO_10646__", "201011L");
-+      Builder.defineMacro("__STDC_MB_MIGHT_NEQ_WC__", "1");
-+      Builder.defineMacro("__STDC_LIB_EXT1__", "201112L");
-+      Builder.defineMacro("__STDC_UTF_16__", "1");
-+      Builder.defineMacro("__STDC_UTF_32__", "1");
-       Builder.defineMacro("__XPG7_THREAD_MODEL__", "1");
-+
-+      if (Opts.C11) {
-+        Builder.defineMacro("__STDC_ANALYZABLE", "1");
-+        Builder.defineMacro("__STDC_IEC_559__", "1");
-+        Builder.defineMacro("__STDC_IEC_559_COMPLEX__", "1");
-+      }
-+
-       Builder.defineMacro("_XPG7", "1");
-       Builder.defineMacro("_XOPEN_SOURCE", "700");
-     } else {
-       Builder.defineMacro("_XOPEN_SOURCE", "500");
-       Builder.defineMacro("__STDC_VERSION__", "199409L");
--      if (Opts.CPlusPlus && !Opts.CPlusPlus11 && !Opts.CPlusPlus14)
--        Builder.defineMacro("__cplusplus", "199711L");
-     }
- 
-     if ((Triple.getArchName() == "i386") || (Triple.getArchName() == "sparc"))
-     Builder.defineMacro("_LARGEFILE_SOURCE");
-     else if ((Triple.getArchName() == "x86_64") ||
-              (Triple.getArchName() == "sparcv9"))
--    Builder.defineMacro("_LARGEFILE64_SOURCE");
-+      Builder.defineMacro("_LARGEFILE64_SOURCE", "1");
- 
-     Builder.defineMacro("__EXTENSIONS__", "1");
--    Builder.defineMacro("_REENTRANT");
-+    Builder.defineMacro("_REENTRANT", "1");
-   }
- 
- public:
-@@ -590,6 +606,10 @@
-     this->WCharType = this->SignedInt;
-     // FIXME: WIntType should be SignedLong
-   }
-+
-+  virtual const char *getStaticInitSectionSpecifier() const override {
-+    return ".init";
-+  }
- };
- 
- // Windows target
---- tools/clang/include/clang/AST/Mangle.h	2014-09-16 08:18:21.000000000 -0700
-+++ tools/clang/include/clang/AST/Mangle.h	2015-10-21 08:10:11.000000000 -0700
-@@ -129,6 +129,8 @@
- 
-   virtual void mangleDynamicInitializer(const VarDecl *D, raw_ostream &) = 0;
- 
-+  virtual void mangleGCCDynamicInitializer(const VarDecl *D, raw_ostream &) = 0;
-+
-   virtual void mangleDynamicAtExitDestructor(const VarDecl *D,
-                                              raw_ostream &) = 0;
- 
---- tools/clang/lib/AST/ItaniumMangle.cpp	2015-10-05 11:01:32.264807353 -0700
-+++ tools/clang/lib/AST/ItaniumMangle.cpp	2016-01-22 19:21:46.574349928 -0800
-@@ -154,6 +154,7 @@
-   void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
-   void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;
-   void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
-+  void mangleGCCDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
-   void mangleDynamicAtExitDestructor(const VarDecl *D,
-                                      raw_ostream &Out) override;
-   void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
-@@ -3834,6 +3835,17 @@
-   Out << "__cxx_global_var_init";
- }
- 
-+void ItaniumMangleContextImpl::mangleGCCDynamicInitializer(const VarDecl *MD,
-+                                                           raw_ostream &Out) {
-+  static unsigned SEQ = 0UL;
-+
-+  // Mangle GCC's __static_initialiation_and_destruction_<X>
-+  // .init_array function.
-+  Out << "_Z41" << "__static_initialization_and_destruction_"
-+    << SEQ << "ii";
-+  ++SEQ;
-+}
-+
- void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
-                                                              raw_ostream &Out) {
-   // Prefix the mangling of D with __dtor_.
---- tools/clang/lib/AST/MicrosoftMangle.cpp	2014-12-21 22:24:49.000000000 -0800
-+++ tools/clang/lib/AST/MicrosoftMangle.cpp	2015-10-21 08:12:50.000000000 -0700
-@@ -132,6 +132,7 @@
-                                 raw_ostream &) override;
-   void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &Out) override;
-   void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
-+  void mangleGCCDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
-   void mangleDynamicAtExitDestructor(const VarDecl *D,
-                                      raw_ostream &Out) override;
-   void mangleStringLiteral(const StringLiteral *SL, raw_ostream &Out) override;
-@@ -2407,6 +2408,11 @@
-   mangleInitFiniStub(D, Out, 'E');
- }
- 
-+void MicrosoftMangleContextImpl::mangleGCCDynamicInitializer(const VarDecl *D,
-+                                                             raw_ostream &Out) {
-+  mangleDynamicInitializer(D, Out);
-+}
-+
- void
- MicrosoftMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
-                                                           raw_ostream &Out) {
---- tools/clang/lib/Frontend/InitPreprocessor.cpp	2016-02-02 07:35:41.701519177 -0800
-+++ tools/clang/lib/Frontend/InitPreprocessor.cpp	2016-02-02 08:45:58.127181898 -0800
-@@ -476,9 +476,16 @@
-   if (!LangOpts.MSVCCompat) {
-     // Currently claim to be compatible with GCC 4.2.1-5621, but only if we're
-     // not compiling for MSVC compatibility
-+    if (TI.getTriple().getOS() == llvm::Triple::Solaris) {
-+      Builder.defineMacro("__GNUC_MINOR__", "8");
-+      Builder.defineMacro("__GNUC_PATCHLEVEL__", "0");
-+    } else {
-     Builder.defineMacro("__GNUC_MINOR__", "2");
-     Builder.defineMacro("__GNUC_PATCHLEVEL__", "1");
-+    }
-+
-     Builder.defineMacro("__GNUC__", "4");
-+
-     // GCC provides a number of C++ ABI Versions in:
-     // ${top_srcdir}/gcc/c-family/c-cppbuiltin.c
-     // Currently valid GXX ABI Versions are documented here:
---- tools/clang/lib/Driver/ToolChains.cpp	2016-02-02 07:35:42.102842090 -0800
-+++ tools/clang/lib/Driver/ToolChains.cpp	2016-02-02 09:01:01.559630875 -0800
-@@ -2923,6 +2923,11 @@
-     DriverArgs.ClaimAllArgs(options::OPT_fuse_init_array);
-   }
- 
-+  if (DriverArgs.getLastArg(options::OPT_fabi_version_EQ) == nullptr)
-+    CC1Args.push_back("-fabi-version=4");
-+  else
-+    DriverArgs.ClaimAllArgs(options::OPT_fabi_version_EQ);
-+
-   if (Arg *A = DriverArgs.getLastArg(options::OPT_mtune_EQ)) {
-     StringRef V = A->getValue();
-     if (!V.empty())
-@@ -2931,7 +2936,7 @@
-     // FIXME: Impplement SPARC target features.
-     CC1Args.push_back(DriverArgs.MakeArgString("-target-feature"));
-     if (Arch == llvm::Triple::sparc || Arch == llvm::Triple::sparcv9) {
--      std::string S = "mtune=";
-+      std::string S = "-mtune=";
-       S += mtune;
-       CC1Args.push_back(DriverArgs.MakeArgString(S.c_str()));
-     } else {
-@@ -2947,7 +2952,7 @@
-     CC1Args.push_back(DriverArgs.MakeArgString("-target-feature"));
- 
-     if ((Arch == llvm::Triple::sparc) || (Arch == llvm::Triple::sparcv9)) {
--      std::string S = "march=";
-+      std::string S = "-march=";
-       S += mtune;
-       CC1Args.push_back(DriverArgs.MakeArgString(S.c_str()));
-     } else {
-@@ -2965,7 +2970,7 @@
-     }
- 
-     CC1Args.push_back(DriverArgs.MakeArgString("-target-feature"));
--    std::string S = "mcpu=";
-+    std::string S = "-mcpu=";
-     S += mcpu;
-     CC1Args.push_back(DriverArgs.MakeArgString(S.c_str()));
- 
---- tools/clang/lib/Driver/Tools.cpp	2016-02-02 07:35:42.107579301 -0800
-+++ tools/clang/lib/Driver/Tools.cpp	2016-02-02 09:00:08.889301970 -0800
-@@ -3000,6 +3000,8 @@
-     StringRef v = A->getValue();
-     CmdArgs.push_back(Args.MakeArgString("-fabi-version=" + v));
-     A->claim();
-+  } else {
-+    CmdArgs.push_back(Args.MakeArgString("-fabi-version=4"));
-   }
- 
-   if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/020-solaris-utils-googletest.patch	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,75 @@
+# 22643565 - llvm's Google test harness needs some attention
+# 3.9.X for upstream.
+--- utils/unittest/googletest/include/gtest/internal/gtest-port.h	2015-04-10 22:11:45.000000000 -0400
++++ utils/unittest/googletest/include/gtest/internal/gtest-port.h	2016-05-08 23:19:20.582431969 -0400
+@@ -238,7 +238,7 @@
+ # endif  // ANDROID
+ #elif defined __MVS__
+ # define GTEST_OS_ZOS 1
+-#elif defined(__sun) && defined(__SVR4)
++#elif defined(__sun) || defined(__sun__)
+ # define GTEST_OS_SOLARIS 1
+ #elif defined(_AIX)
+ # define GTEST_OS_AIX 1
+--- utils/unittest/googletest/src/gtest-port.cc	2013-11-18 19:57:56.000000000 -0500
++++ utils/unittest/googletest/src/gtest-port.cc	2016-05-08 23:19:20.582431969 -0400
+@@ -51,6 +51,13 @@
+ # include <mach/vm_map.h>
+ #endif  // GTEST_OS_MAC
+ 
++#if GTEST_OS_SOLARIS
++# include <strings.h>
++# include <sys/types.h>
++# include <dirent.h>
++# include <unistd.h>
++#endif
++
+ #include "gtest/gtest-spi.h"
+ #include "gtest/gtest-message.h"
+ #include "gtest/internal/gtest-internal.h"
+@@ -77,7 +84,7 @@
+ const int kStdErrFileno = STDERR_FILENO;
+ #endif  // _MSC_VER
+ 
+-#if GTEST_OS_MAC
++#if defined(GTEST_OS_MAC)
+ 
+ // Returns the number of threads running in the process, or 0 to indicate that
+ // we cannot detect it.
+@@ -98,6 +105,36 @@
+   }
+ }
+ 
++#elif defined(GTEST_OS_SOLARIS)
++
++size_t GetThreadCount() {
++  size_t NumThreads = 1U;
++  char lwpdir[PATH_MAX+1];
++
++  (void) std::memset(lwpdir, 0, sizeof(lwpdir));
++  (void) std::sprintf(lwpdir, "/proc/%i/lwp/", static_cast<int>(getpid()));
++
++  struct dirent *DE;
++  DIR *D = ::opendir(lwpdir);
++  if (!D)
++    return NumThreads;
++
++  while ((DE = ::readdir(D)) != NULL) {
++    if (DE->d_name[0] == '.') {
++      if ((DE->d_name[1] == '\0') ||
++          ((DE->d_name[1] == '.') && (DE->d_name[2] == '\0')))
++        continue;
++    }
++
++    NumThreads =
++      static_cast<size_t>(std::max<int>(NumThreads, std::atoi(DE->d_name)));
++  }
++
++  ::rewinddir(D);
++  ::closedir(D);
++  return NumThreads;
++}
++
+ #else
+ 
+ size_t GetThreadCount() {
--- a/components/llvm/patches/021-llvm-ilist-iterator-22031298.patch	Thu Jul 28 16:15:45 2016 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,13055 +0,0 @@
-# http://lists.llvm.org/pipermail/llvm-dev/2015-October/091115.html
-# - 22031298 - toxic bugs in LLVM ilist/plist end up eliminating entire
-# MachineBasicBlocks
-# - Presumed fixed (?) in trunk upstream. Not verified.
-# - Verified fixed in our 3.6.2 fork.
-# Not for upstream. Autoconf-based built system is removed in 3.8.X.
---- Makefile.rules	2015-10-05 11:01:32.687305595 -0700
-+++ Makefile.rules	2015-12-08 11:12:41.094567698 -0800
-@@ -331,6 +331,12 @@
-  endif
- endif
- 
-+ifeq ($(HOST_OS), $(filter $(HOST_OS), SunOS))
-+  REQUIRES_EH := 1
-+else
-+  REQUIRES_EH := 0
-+endif
-+
- ifeq ($(ENABLE_WERROR),1)
-   CXX.Flags += -Werror
-   C.Flags += -Werror
-@@ -355,14 +361,16 @@
- endif
- 
- # IF REQUIRES_EH=1 is specified then don't disable exceptions
--ifndef REQUIRES_EH
-+ifneq ($(REQUIRES_EH), 1)
-+  REQUIRES_RTTI := 0
-   CXX.Flags += -fno-exceptions
- else
-   # If the library requires EH, it also requires RTTI.
-   REQUIRES_RTTI := 1
-+  CXX.Flags += -fexceptions
- endif
- 
--ifdef REQUIRES_FRAME_POINTER
-+ifeq ($(REQUIRES_FRAME_POINTER), 1)
-   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))
-@@ -371,6 +379,8 @@
- # If REQUIRES_RTTI=1 is specified then don't disable run-time type id.
- ifneq ($(REQUIRES_RTTI), 1)
-   CXX.Flags += -fno-rtti
-+else
-+  CXX.Flags += -frtti
- endif
- 
- ifeq ($(ENABLE_COVERAGE),1)
---- include/llvm/ADT/DenseMap.h	2015-10-05 11:01:32.000000000 -0700
-+++ include/llvm/ADT/DenseMap.h	2016-01-24 14:13:03.000000000 -0800
-@@ -254,7 +254,7 @@
-   DenseMapBase() {}
- 
-   void destroyAll() {
--    if ((getNumBuckets() == 0) || empty()) // Nothing to do.
-+    if (getNumBuckets() == 0) // Nothing to do.
-       return;
- 
-     const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
-@@ -264,10 +264,6 @@
-         P->getSecond().~ValueT();
-       P->getFirst().~KeyT();
-     }
--
--#ifndef NDEBUG
--    memset((void*)getBuckets(), 0x5a, sizeof(BucketT)*getNumBuckets());
--#endif
-   }
- 
-   void initEmpty() {
-@@ -856,7 +852,8 @@
- 
-       // First move the inline buckets into a temporary storage.
-       AlignedCharArrayUnion<BucketT[InlineBuckets]> TmpStorage;
--      BucketT *TmpBegin = reinterpret_cast<BucketT *>(TmpStorage.buffer);
-+      BucketT *TmpBegin =
-+        reinterpret_cast<BucketT*>(reinterpret_cast<void*>(TmpStorage.buffer));
-       BucketT *TmpEnd = TmpBegin;
- 
-       // Loop over the buckets, moving non-empty, non-tombstones into the
-@@ -940,17 +937,22 @@
-     // 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);
-+    return reinterpret_cast<const BucketT*>(
-+      reinterpret_cast<const void*>(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);
-+    return reinterpret_cast<const LargeRep*>(
-+      reinterpret_cast<const void*>(storage.buffer));
-   }
-+
-   LargeRep *getLargeRep() {
-     return const_cast<LargeRep *>(
-       const_cast<const SmallDenseMap *>(this)->getLargeRep());
---- include/llvm/ADT/Optional.h	2014-09-30 19:12:35.000000000 -0700
-+++ include/llvm/ADT/Optional.h	2015-12-07 14:59:03.998240128 -0800
-@@ -163,16 +163,34 @@
-     reset();
-   }
- 
--  const T* getPointer() const { assert(hasVal); return reinterpret_cast<const T*>(storage.buffer); }
--  T* getPointer() { assert(hasVal); return reinterpret_cast<T*>(storage.buffer); }
--  const T& getValue() const LLVM_LVALUE_FUNCTION { assert(hasVal); return *getPointer(); }
-+  const T* getPointer() const {
-+    assert(hasVal);
-+    return reinterpret_cast<const T*>(
-+      reinterpret_cast<const void*>(storage.buffer));
-+  }
-+
-+  T* getPointer() {
-+    assert(hasVal);
-+    return reinterpret_cast<T*>(
-+      reinterpret_cast<void*>(storage.buffer));
-+  }
-+
-+  const T& getValue() const LLVM_LVALUE_FUNCTION {
-+    assert(hasVal);
-+    return *getPointer();
-+  }
-+
-   T& getValue() LLVM_LVALUE_FUNCTION { assert(hasVal); return *getPointer(); }
- 
-   LLVM_EXPLICIT operator bool() const { return hasVal; }
-   bool hasValue() const { return hasVal; }
-   const T* operator->() const { return getPointer(); }
-   T* operator->() { return getPointer(); }
--  const T& operator*() const LLVM_LVALUE_FUNCTION { assert(hasVal); return *getPointer(); }
-+  const T& operator*() const LLVM_LVALUE_FUNCTION {
-+    assert(hasVal);
-+    return *getPointer();
-+  }
-+
-   T& operator*() LLVM_LVALUE_FUNCTION { assert(hasVal); return *getPointer(); }
- 
-   template <typename U>
---- include/llvm/ADT/ilist.h	2014-07-28 17:38:55.000000000 -0700
-+++ include/llvm/ADT/ilist.h	2015-11-10 13:51:33.696789150 -0800
-@@ -104,6 +104,53 @@
-   }
- };
- 
-+template <typename NodeTy> class ilist_half_node;
-+template <typename NodeTy> class ilist_node;
-+
-+/// Traits with an embedded ilist_node as a sentinel.
-+///
-+/// FIXME: The downcast in createSentinel() is UB.
-+template <typename NodeTy> struct ilist_embedded_sentinel_traits {
-+  /// Get hold of the node that marks the end of the list.
-+  NodeTy *createSentinel() const {
-+    // Since i(p)lists always publicly derive from their corresponding traits,
-+    // placing a data member in this class will augment the i(p)list.  But since
-+    // the NodeTy is expected to be publicly derive from ilist_node<NodeTy>,
-+    // there is a legal viable downcast from it to NodeTy. We use this trick to
-+    // superimpose an 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<NodeTy *>(&Sentinel);
-+  }
-+  static void destroySentinel(NodeTy *) {}
-+
-+  NodeTy *provideInitialHead() const { return createSentinel(); }
-+  NodeTy *ensureHead(NodeTy *) const { return createSentinel(); }
-+  static void noteHead(NodeTy *, NodeTy *) {}
-+
-+private:
-+  mutable ilist_node<NodeTy> Sentinel;
-+};
-+
-+/// Trait with an embedded ilist_half_node as a sentinel.
-+///
-+/// FIXME: The downcast in createSentinel() is UB.
-+template <typename NodeTy> struct ilist_half_embedded_sentinel_traits {
-+  /// Get hold of the node that marks the end of the list.
-+  NodeTy *createSentinel() const {
-+    // See comment in ilist_embedded_sentinel_traits::createSentinel().
-+    return static_cast<NodeTy *>(&Sentinel);
-+  }
-+  static void destroySentinel(NodeTy *) {}
-+
-+  NodeTy *provideInitialHead() const { return createSentinel(); }
-+  NodeTy *ensureHead(NodeTy *) const { return createSentinel(); }
-+  static void noteHead(NodeTy *, NodeTy *) {}
-+
-+private:
-+  mutable ilist_half_node<NodeTy> Sentinel;
-+};
-+
- /// ilist_node_traits - A fragment for template traits for intrusive list
- /// that provides default node related operations.
- ///
-@@ -173,8 +220,8 @@
-   template<class T> void operator-(T) const;
- public:
- 
--  ilist_iterator(pointer NP) : NodePtr(NP) {}
--  ilist_iterator(reference NR) : NodePtr(&NR) {}
-+  explicit ilist_iterator(pointer NP) : NodePtr(NP) {}
-+  explicit ilist_iterator(reference NR) : NodePtr(&NR) {}
-   ilist_iterator() : NodePtr(nullptr) {}
- 
-   // This is templated so that we can allow constructing a const iterator from
-@@ -191,8 +238,10 @@
-     return *this;
-   }
- 
-+  void reset(pointer NP) { NodePtr = NP; }
-+
-   // Accessors...
--  operator pointer() const {
-+  explicit operator pointer() const {
-     return NodePtr;
-   }
- 
-@@ -237,14 +286,14 @@
- // These are to catch errors when people try to use them as random access
- // iterators.
- template<typename T>
--void operator-(int, ilist_iterator<T>) LLVM_DELETED_FUNCTION;
-+void operator-(int, ilist_iterator<T>) = delete;
- template<typename T>
--void operator-(ilist_iterator<T>,int) LLVM_DELETED_FUNCTION;
-+void operator-(ilist_iterator<T>,int) = delete;
- 
- template<typename T>
--void operator+(int, ilist_iterator<T>) LLVM_DELETED_FUNCTION;
-+void operator+(int, ilist_iterator<T>) = delete;
- template<typename T>
--void operator+(ilist_iterator<T>,int) LLVM_DELETED_FUNCTION;
-+void operator+(ilist_iterator<T>,int) = delete;
- 
- // operator!=/operator== - Allow mixed comparisons without dereferencing
- // the iterator, which could very likely be pointing to end().
-@@ -332,8 +381,8 @@
- 
-   // 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;
-+  iplist(const iplist &) = delete;
-+  void operator=(const iplist &) = delete;
- 
- public:
-   typedef NodeTy *pointer;
-@@ -422,7 +471,7 @@
-     this->setPrev(CurNode, New);
- 
-     this->addNodeToList(New);  // Notify traits that we added a node...
--    return New;
-+    return iterator(New);
-   }
- 
-   iterator insertAfter(iterator where, NodeTy *New) {
-@@ -443,7 +492,7 @@
-     else
-       Head = NextNode;
-     this->setPrev(NextNode, PrevNode);
--    IT = NextNode;
-+    IT.reset(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
-@@ -461,12 +510,18 @@
-     return remove(MutIt);
-   }
- 
-+  NodeTy *remove(NodeTy *IT) { return remove(iterator(IT)); }
-+  NodeTy *remove(NodeTy &IT) { return remove(iterator(IT)); }
-+
-   // erase - remove a node from the controlled sequence... and delete it.
-   iterator erase(iterator where) {
-     this->deleteNode(remove(where));
-     return where;
-   }
- 
-+  iterator erase(NodeTy *IT) { return erase(iterator(IT)); }
-+  iterator erase(NodeTy &IT) { return erase(iterator(IT)); }
-+
-   /// Remove all nodes from the list like clear(), but do not call
-   /// removeNodeFromList() or deleteNode().
-   ///
-@@ -522,7 +577,7 @@
-       this->setNext(Last, PosNext);
-       this->setPrev(PosNext, Last);
- 
--      this->transferNodesFromList(L2, First, PosNext);
-+      this->transferNodesFromList(L2, iterator(First), iterator(PosNext));
- 
-       // Now that everything is set, restore the pointers to the list sentinels.
-       L2.setTail(L2Sentinel);
-@@ -579,6 +634,59 @@
-   void splice(iterator where, iplist &L2, iterator first, iterator last) {
-     if (first != last) transfer(where, L2, first, last);
-   }
-+  void splice(iterator where, iplist &L2, NodeTy &N) {
-+    splice(where, L2, iterator(N));
-+  }
-+  void splice(iterator where, iplist &L2, NodeTy *N) {
-+    splice(where, L2, iterator(N));
-+  }
-+
-+  template <class Compare>
-+  void merge(iplist &Right, Compare comp) {
-+    if (this == &Right)
-+      return;
-+    iterator First1 = begin(), Last1 = end();
-+    iterator First2 = Right.begin(), Last2 = Right.end();
-+    while (First1 != Last1 && First2 != Last2) {
-+      if (comp(*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 Compare>
-+  void sort(Compare comp) {
-+    // The list is empty, vacuously sorted.
-+    if (empty())
-+      return;
-+    // The list has a single element, vacuously sorted.
-+    if (std::next(begin()) == end())
-+      return;
-+    // Find the split point for the list.
-+    iterator Center = begin(), End = begin();
-+    while (End != end() && std::next(End) != end()) {
-+      Center = std::next(Center);
-+      End = std::next(std::next(End));
-+    }
-+    // Split the list into two.
-+    iplist RightHalf;
-+    RightHalf.splice(RightHalf.begin(), *this, Center, end());
-+
-+    // Sort the two sublists.
-+    sort(comp);
-+    RightHalf.sort(comp);
-+
-+    // Merge the two sublists back together.
-+    merge(RightHalf, comp);
-+  }
-+  void sort() { sort(op_less); }
- };
- 
- 
---- include/llvm/ADT/ilist_node.h	2014-08-13 09:26:38.000000000 -0700
-+++ include/llvm/ADT/ilist_node.h	2015-11-02 09:17:47.446456035 -0800
-@@ -19,12 +19,15 @@
- 
- template<typename NodeTy>
- struct ilist_traits;
-+template <typename NodeTy> struct ilist_embedded_sentinel_traits;
-+template <typename NodeTy> struct ilist_half_embedded_sentinel_traits;
- 
- /// ilist_half_node - Base class that provides prev services for sentinels.
- ///
- template<typename NodeTy>
- class ilist_half_node {
-   friend struct ilist_traits<NodeTy>;
-+  friend struct ilist_half_embedded_sentinel_traits<NodeTy>;
-   NodeTy *Prev;
- protected:
-   NodeTy *getPrev() { return Prev; }
-@@ -36,6 +39,8 @@
- template<typename NodeTy>
- struct ilist_nextprev_traits;
- 
-+template <typename NodeTy> class ilist_iterator;
-+
- /// ilist_node - Base class that provides next/prev services for nodes
- /// that use ilist_nextprev_traits or ilist_default_traits.
- ///
-@@ -43,6 +48,8 @@
- class ilist_node : private ilist_half_node<NodeTy> {
-   friend struct ilist_nextprev_traits<NodeTy>;
-   friend struct ilist_traits<NodeTy>;
-+  friend struct ilist_half_embedded_sentinel_traits<NodeTy>;
-+  friend struct ilist_embedded_sentinel_traits<NodeTy>;
-   NodeTy *Next;
-   NodeTy *getNext() { return Next; }
-   const NodeTy *getNext() const { return Next; }
-@@ -51,6 +58,15 @@
-   ilist_node() : Next(nullptr) {}
- 
- public:
-+  ilist_iterator<NodeTy> getIterator() {
-+    // FIXME: Stop downcasting to create the iterator (potential UB).
-+    return ilist_iterator<NodeTy>(static_cast<NodeTy *>(this));
-+  }
-+  ilist_iterator<const NodeTy> getIterator() const {
-+    // FIXME: Stop downcasting to create the iterator (potential UB).
-+    return ilist_iterator<const NodeTy>(static_cast<const NodeTy *>(this));
-+  }
-+
-   /// @name Adjacent Node Accessors
-   /// @{
- 
---- include/llvm/CodeGen/CommandFlags.h	2015-01-13 21:24:33.000000000 -0800
-+++ include/llvm/CodeGen/CommandFlags.h	2016-01-26 14:46:39.000000000 -0800
-@@ -31,7 +31,7 @@
- MCPU("mcpu",
-      cl::desc("Target a specific cpu type (-mcpu=help for details)"),
-      cl::value_desc("cpu-name"),
--     cl::init(""));
-+     cl::init(std::string("")));
- 
- cl::list<std::string>
- MAttrs("mattr",
-@@ -177,7 +177,7 @@
- cl::opt<std::string>
- TrapFuncName("trap-func", cl::Hidden,
-         cl::desc("Emit a call to trap function rather than a trap instruction"),
--        cl::init(""));
-+        cl::init(std::string("")));
- 
- cl::opt<bool>
- EnablePIE("enable-pie",
-@@ -192,11 +192,11 @@
- cl::opt<std::string> StopAfter("stop-after",
-                             cl::desc("Stop compilation after a specific pass"),
-                             cl::value_desc("pass-name"),
--                                      cl::init(""));
-+                                      cl::init(std::string("")));
- cl::opt<std::string> StartAfter("start-after",
-                           cl::desc("Resume compilation after a specific pass"),
-                           cl::value_desc("pass-name"),
--                          cl::init(""));
-+                          cl::init(std::string("")));
- 
- cl::opt<bool> DataSections("data-sections",
-                            cl::desc("Emit data into separate sections"),
-@@ -258,7 +258,7 @@
- // CFI.
- cl::opt<std::string>
- CFIFuncName("cfi-func-name", cl::desc("The name of the CFI function to call"),
--            cl::init(""));
-+            cl::init(std::string("")));
- 
- // Common utility function tightly tied to the options listed here. Initializes
- // a TargetOptions object with CodeGen flags and returns it.
---- include/llvm/CodeGen/MachineBasicBlock.h	2014-11-13 16:34:59.000000000 -0800
-+++ include/llvm/CodeGen/MachineBasicBlock.h	2015-12-06 12:31:19.423838338 -0800
-@@ -165,7 +165,7 @@
-     Ty &operator*() const { return *MII; }
-     Ty *operator->() const { return &operator*(); }
- 
--    operator Ty*() const { return MII; }
-+    operator Ty*() const { return MII.getNodePtrUnchecked(); }
- 
-     bool operator==(const bundle_iterator &x) const {
-       return MII == x.MII;
---- include/llvm/CodeGen/MachineFunction.h	2015-01-06 12:05:02.000000000 -0800
-+++ include/llvm/CodeGen/MachineFunction.h	2015-12-06 20:18:16.623633498 -0800
-@@ -352,12 +352,10 @@
-     BasicBlocks.splice(InsertPt, BasicBlocks, MBBI, MBBE);
-   }
- 
--  void remove(iterator MBBI) {
--    BasicBlocks.remove(MBBI);
--  }
--  void erase(iterator MBBI) {
--    BasicBlocks.erase(MBBI);
--  }
-+  void remove(iterator MBBI) { BasicBlocks.remove(MBBI); }
-+  void remove(MachineBasicBlock *MBBI) { BasicBlocks.remove(MBBI); }
-+  void erase(iterator MBBI) { BasicBlocks.erase(MBBI); }
-+  void erase(MachineBasicBlock *MBBI) { BasicBlocks.erase(MBBI); }
- 
-   //===--------------------------------------------------------------------===//
-   // Internal functions used to automatically number MachineBasicBlocks
---- include/llvm/CodeGen/MachineInstrBuilder.h	2014-10-31 16:19:46.000000000 -0700
-+++ include/llvm/CodeGen/MachineInstrBuilder.h	2015-12-06 13:48:56.344154780 -0800
-@@ -280,7 +280,7 @@
-                                    const MCInstrDesc &MCID,
-                                    unsigned DestReg) {
-   if (I->isInsideBundle()) {
--    MachineBasicBlock::instr_iterator MII = I;
-+    MachineBasicBlock::instr_iterator MII(I);
-     return BuildMI(BB, MII, DL, MCID, DestReg);
-   }
- 
-@@ -317,7 +317,7 @@
-                                    DebugLoc DL,
-                                    const MCInstrDesc &MCID) {
-   if (I->isInsideBundle()) {
--    MachineBasicBlock::instr_iterator MII = I;
-+    MachineBasicBlock::instr_iterator MII(I);
-     return BuildMI(BB, MII, DL, MCID);
-   }
- 
-@@ -472,7 +472,7 @@
-     if (I == Begin) {
-       if (!empty())
-         MI->bundleWithSucc();
--      Begin = MI;
-+      Begin = MI->getIterator();
-       return *this;
-     }
-     if (I == End) {
---- include/llvm/CodeGen/MachineInstrBundle.h	2014-04-13 17:51:57.000000000 -0700
-+++ include/llvm/CodeGen/MachineInstrBundle.h	2015-12-06 12:35:51.016366535 -0800
-@@ -44,23 +44,23 @@
- /// getBundleStart - Returns the first instruction in the bundle containing MI.
- ///
- inline MachineInstr *getBundleStart(MachineInstr *MI) {
--  MachineBasicBlock::instr_iterator I = MI;
-+  MachineBasicBlock::instr_iterator I(MI);
-   while (I->isBundledWithPred())
-     --I;
--  return I;
-+  return &*I;
- }
- 
- inline const MachineInstr *getBundleStart(const MachineInstr *MI) {
--  MachineBasicBlock::const_instr_iterator I = MI;
-+  MachineBasicBlock::const_instr_iterator I(MI);
-   while (I->isBundledWithPred())
-     --I;
--  return I;
-+  return &*I;
- }
- 
- /// Return an iterator pointing beyond the bundle containing MI.
- inline MachineBasicBlock::instr_iterator
- getBundleEnd(MachineInstr *MI) {
--  MachineBasicBlock::instr_iterator I = MI;
-+  MachineBasicBlock::instr_iterator I(MI);
-   while (I->isBundledWithSucc())
-     ++I;
-   return ++I;
-@@ -69,7 +69,7 @@
- /// Return an iterator pointing beyond the bundle containing MI.
- inline MachineBasicBlock::const_instr_iterator
- getBundleEnd(const MachineInstr *MI) {
--  MachineBasicBlock::const_instr_iterator I = MI;
-+  MachineBasicBlock::const_instr_iterator I(MI);
-   while (I->isBundledWithSucc())
-     ++I;
-   return ++I;
-@@ -116,10 +116,10 @@
-   ///
-   explicit MachineOperandIteratorBase(MachineInstr *MI, bool WholeBundle) {
-     if (WholeBundle) {
--      InstrI = getBundleStart(MI);
-+      InstrI = getBundleStart(MI)->getIterator();
-       InstrE = MI->getParent()->instr_end();
-     } else {
--      InstrI = InstrE = MI;
-+      InstrI = InstrE = MI->getIterator();
-       ++InstrE;
-     }
-     OpI = InstrI->operands_begin();
---- include/llvm/CodeGen/SlotIndexes.h	2014-04-13 17:51:57.000000000 -0700
-+++ include/llvm/CodeGen/SlotIndexes.h	2015-12-06 13:26:01.031361628 -0800
-@@ -427,11 +427,11 @@
-     /// Returns the next non-null index, if one exists.
-     /// Otherwise returns getLastIndex().
-     SlotIndex getNextNonNullIndex(SlotIndex Index) {
--      IndexList::iterator I = Index.listEntry();
-+      IndexList::iterator I = Index.listEntry()->getIterator();
-       IndexList::iterator E = indexList.end();
-       while (++I != E)
-         if (I->getInstr())
--          return SlotIndex(I, Index.getSlot());
-+          return SlotIndex(&*I, Index.getSlot());
-       // We reached the end of the function.
-       return getLastIndex();
-     }
-@@ -580,11 +580,11 @@
-       IndexList::iterator prevItr, nextItr;
-       if (Late) {
-         // Insert mi's index immediately before the following instruction.
--        nextItr = getIndexAfter(mi).listEntry();
-+        nextItr = getIndexAfter(mi).listEntry()->getIterator();
-         prevItr = std::prev(nextItr);
-       } else {
-         // Insert mi's index immediately after the preceding instruction.
--        prevItr = getIndexBefore(mi).listEntry();
-+        prevItr = getIndexBefore(mi).listEntry()->getIterator();
-         nextItr = std::next(prevItr);
-       }
- 
-@@ -646,11 +646,11 @@
-       if (nextMBB == mbb->getParent()->end()) {
-         startEntry = &indexList.back();
-         endEntry = createEntry(nullptr, 0);
--        newItr = indexList.insertAfter(startEntry, endEntry);
-+        newItr = indexList.insertAfter(startEntry->getIterator(), endEntry);
-       } else {
-         startEntry = createEntry(nullptr, 0);
--        endEntry = getMBBStartIdx(nextMBB).listEntry();
--        newItr = indexList.insert(endEntry, startEntry);
-+        endEntry = getMBBStartIdx(&*nextMBB).listEntry();
-+        newItr = indexList.insert(endEntry->getIterator(), startEntry);
-       }
- 
-       SlotIndex startIdx(startEntry, SlotIndex::Slot_Block);
---- include/llvm/IR/IRBuilder.h	2014-12-30 06:28:14.000000000 -0800
-+++ include/llvm/IR/IRBuilder.h	2015-11-24 09:08:00.970126898 -0800
-@@ -58,9 +58,10 @@
-   FastMathFlags FMF;
- public:
- 
--  IRBuilderBase(LLVMContext &context, MDNode *FPMathTag = nullptr)
--    : Context(context), DefaultFPMathTag(FPMathTag), FMF() {
--    ClearInsertionPoint();
-+  IRBuilderBase(LLVMContext &Ctx, MDNode *FPMathTag = nullptr)
-+    : CurDbgLocation(), BB(nullptr), InsertPt(),
-+    Context(Ctx), DefaultFPMathTag(FPMathTag), FMF() {
-+    // ClearInsertionPoint();
-   }
- 
-   //===--------------------------------------------------------------------===//
-@@ -71,7 +72,7 @@
-   /// inserted into a block.
-   void ClearInsertionPoint() {
-     BB = nullptr;
--    InsertPt = nullptr;
-+    InsertPt.reset(nullptr);
-   }
- 
-   BasicBlock *GetInsertBlock() const { return BB; }
-@@ -89,8 +90,8 @@
-   /// the specified instruction.
-   void SetInsertPoint(Instruction *I) {
-     BB = I->getParent();
--    InsertPt = I;
--    assert(I != BB->end() && "Can't read debug loc from end()");
-+    InsertPt = I->getIterator();
-+    assert(InsertPt != BB->end() && "Can't read debug loc from end()");
-     SetCurrentDebugLocation(I->getDebugLoc());
-   }
- 
-@@ -99,6 +100,8 @@
-   void SetInsertPoint(BasicBlock *TheBB, BasicBlock::iterator IP) {
-     BB = TheBB;
-     InsertPt = IP;
-+    if (IP != TheBB->end())
-+      SetCurrentDebugLocation(IP->getDebugLoc());
-   }
- 
-   /// \brief Find the nearest point that dominates this use, and specify that
-@@ -107,10 +110,12 @@
-     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());
-+      TerminatorInst *TI = PredBB->getTerminator();
-+      assert(U != TI && "critical edge not split");
-+      SetInsertPoint(PredBB, TI->getIterator());
-       return;
-     }
-+
-     SetInsertPoint(UseInst);
-   }
- 
---- include/llvm/IR/Metadata.h	2015-10-05 11:01:32.758196248 -0700
-+++ include/llvm/IR/Metadata.h	2015-11-27 09:20:10.357775627 -0800
-@@ -927,6 +927,71 @@
-   using ReplaceableMetadataImpl::replaceAllUsesWith;
- };
- 
-+template <class T>
-+class TypedMDOperandIterator : public std::iterator<std::input_iterator_tag, T*, std::ptrdiff_t, void, T*> {
-+private:
-+  MDNode::op_iterator I = nullptr;
-+
-+public:
-+  TypedMDOperandIterator() = default;
-+  explicit TypedMDOperandIterator(MDNode::op_iterator I) : I(I) {}
-+  ~TypedMDOperandIterator() { }
-+
-+  T *operator*() const { return cast_or_null<T>(*I); }
-+
-+  TypedMDOperandIterator &operator++() {
-+    ++I;
-+    return *this;
-+  }
-+
-+  TypedMDOperandIterator operator++(int) {
-+    TypedMDOperandIterator Temp(*this);
-+    ++I;
-+    return Temp;
-+  }
-+
-+  bool operator==(const TypedMDOperandIterator &X) const { return I == X.I; }
-+  bool operator!=(const TypedMDOperandIterator &X) const { return I != X.I; }
-+};
-+
-+template<class T> class MDTupleTypedArrayWrapper {
-+private:
-+  const MDTuple *N = nullptr;
-+
-+public:
-+  MDTupleTypedArrayWrapper() = default;
-+  MDTupleTypedArrayWrapper(const MDTuple *N) : N(N) {}
-+  ~MDTupleTypedArrayWrapper() { }
-+
-+  template<class U>
-+  MDTupleTypedArrayWrapper(const MDTupleTypedArrayWrapper<U> &Other,
-+                           typename std::enable_if<std::is_convertible<U*, T*>::value>::type* = nullptr)
-+  : N(Other.get()) { }
-+
-+  template<class U>
-+  explicit MDTupleTypedArrayWrapper(const MDTupleTypedArrayWrapper<U> &Other,
-+                                    typename std::enable_if<!std::is_convertible<U*, T*>::value>::type* = nullptr)
-+  : N(Other.get()) { }
-+
-+  explicit operator bool() const { return get(); }
-+  explicit operator MDTuple *() const { return get(); }
-+
-+  MDTuple *get() const { return const_cast<MDTuple *>(N); }
-+  MDTuple *operator->() const { return get(); }
-+  MDTuple &operator*() const { return *get(); }
-+
-+  unsigned size() const { return N ? N->getNumOperands() : 0u; }
-+  T *operator[](unsigned I) const { return cast_or_null<T>(N->getOperand(I)); }
-+
-+  typedef TypedMDOperandIterator<T> iterator;
-+  iterator begin() const { return N ? iterator(N->op_begin()) : iterator(); }
-+  iterator end() const { return N ? iterator(N->op_end()) : iterator(); }
-+};
-+
-+#define HANDLE_METADATA(CLASS)                                                 \
-+  typedef MDTupleTypedArrayWrapper<CLASS> CLASS##Array;
-+#include "llvm/IR/Metadata.def"
-+
- //===----------------------------------------------------------------------===//
- /// \brief A tuple of MDNodes.
- ///
---- include/llvm/MC/MCSection.h	2013-04-17 14:18:16.000000000 -0700
-+++ include/llvm/MC/MCSection.h	2015-12-07 12:32:38.557027450 -0800
-@@ -15,6 +15,9 @@
- #define LLVM_MC_MCSECTION_H
- 
- #include "llvm/ADT/StringRef.h"
-+#include "llvm/ADT/ilist.h"
-+#include "llvm/ADT/ilist_node.h"
-+#include "llvm/MC/MCAssembler.h"
- #include "llvm/MC/SectionKind.h"
- #include "llvm/Support/Compiler.h"
- 
-@@ -41,6 +44,14 @@
-     MCSection(SectionVariant V, SectionKind K) : Variant(V), Kind(K) {}
-     SectionVariant Variant;
-     SectionKind Kind;
-+
-+  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;
-+
-   public:
-     virtual ~MCSection();
- 
---- include/llvm/MC/MCTargetOptionsCommandFlags.h	2015-01-14 03:23:27.000000000 -0800
-+++ include/llvm/MC/MCTargetOptionsCommandFlags.h	2016-01-26 19:29:37.000000000 -0800
-@@ -43,7 +43,7 @@
- cl::opt<std::string>
- ABIName("target-abi", cl::Hidden,
-         cl::desc("The name of the ABI to be targeted from the backend."),
--        cl::init(""));
-+        cl::init(std::string("")));
- 
- static inline MCTargetOptions InitMCTargetOptionsFromFlags() {
-   MCTargetOptions Options;
---- include/llvm/Support/GenericDomTree.h	2015-01-14 02:33:21.000000000 -0800
-+++ include/llvm/Support/GenericDomTree.h	2015-12-08 09:12:30.450453075 -0800
-@@ -715,7 +715,11 @@
-   /// recalculate - compute a dominator tree for the given function
-   template <class FT> void recalculate(FT &F) {
-     typedef GraphTraits<FT *> TraitsTy;
-+    typedef typename GraphTraits<FT*>::ChildIteratorType TraitsTyChildIterator;
-+    typedef typename GraphTraits<FT*>::nodes_iterator TraitsTyNodeIterator;
-+
-     reset();
-+
-     this->Vertex.push_back(nullptr);
- 
-     if (!this->IsPostDominators) {
-@@ -728,19 +732,22 @@
-       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);
-+      for (TraitsTyNodeIterator I = TraitsTy::nodes_begin(&F),
-+                                E = TraitsTy::nodes_end(&F);
-            I != E; ++I) {
--        if (TraitsTy::child_begin(I) == TraitsTy::child_end(I))
--          addRoot(I);
-+        TraitsTyChildIterator ChildBegin(TraitsTy::child_begin(&*I));
-+        TraitsTyChildIterator ChildEnd(TraitsTy::child_end(&*I));
-+
-+        if (ChildBegin == ChildEnd)
-+          addRoot(&*I);
- 
-         // Prepopulate maps so that we don't get iterator invalidation issues
-         // later.
--        this->IDoms[I] = nullptr;
--        this->DomTreeNodes[I] = nullptr;
-+        this->IDoms[&*I] = nullptr;
-+        this->DomTreeNodes[&*I] = nullptr;
-       }
- 
--      Calculate<FT, Inverse<NodeT *>>(*this, F);
-+      Calculate<FT, Inverse<NodeT*> >(*this, F);
-     }
-   }
- };
---- include/llvm/Transforms/Utils/SSAUpdaterImpl.h	2014-04-21 15:55:11.000000000 -0700
-+++ include/llvm/Transforms/Utils/SSAUpdaterImpl.h	2015-11-29 13:46:28.070241785 -0800
-@@ -378,7 +378,7 @@
-   void FindExistingPHI(BlkT *BB, BlockListTy *BlockList) {
-     for (typename BlkT::iterator BBI = BB->begin(), BBE = BB->end();
-          BBI != BBE; ++BBI) {
--      PhiT *SomePHI = Traits::InstrIsPHI(BBI);
-+      PhiT *SomePHI = Traits::InstrIsPHI(&*BBI);
-       if (!SomePHI)
-         break;
-       if (CheckIfPHIMatches(SomePHI)) {
---- lib/Analysis/AliasAnalysisEvaluator.cpp	2014-07-24 05:16:19.000000000 -0700
-+++ lib/Analysis/AliasAnalysisEvaluator.cpp	2015-11-27 17:10:53.853958210 -0800
-@@ -146,9 +146,9 @@
-   SetVector<Value *> Loads;
-   SetVector<Value *> Stores;
- 
--  for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
--    if (I->getType()->isPointerTy())    // Add all pointer arguments.
--      Pointers.insert(I);
-+  for (auto &I : F.args())
-+    if (I.getType()->isPointerTy())    // Add all pointer arguments.
-+      Pointers.insert(&I);
- 
-   for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
-     if (I->getType()->isPointerTy()) // Add all pointer instructions.
---- lib/Analysis/AliasAnalysis.cpp	2014-12-15 06:09:53.000000000 -0800
-+++ lib/Analysis/AliasAnalysis.cpp	2015-11-27 09:33:58.058293495 -0800
-@@ -501,12 +501,12 @@
-                                               const ModRefResult Mode) {
-   assert(I1.getParent() == I2.getParent() &&
-          "Instructions not in same basic block!");
--  BasicBlock::const_iterator I = &I1;
--  BasicBlock::const_iterator E = &I2;
-+  BasicBlock::const_iterator I = I1.getIterator();
-+  BasicBlock::const_iterator E = I2.getIterator();
-   ++E;  // Convert from inclusive to exclusive range.
- 
-   for (; I != E; ++I) // Check every instruction in range
--    if (getModRefInfo(I, Loc) & Mode)
-+    if (getModRefInfo(&(*I), Loc) & Mode)
-       return true;
-   return false;
- }
---- lib/Analysis/AliasSetTracker.cpp	2014-11-19 11:36:18.000000000 -0800
-+++ lib/Analysis/AliasSetTracker.cpp	2015-11-27 09:52:20.756423865 -0800
-@@ -229,8 +229,8 @@
-     iterator Cur = I++;
-     if (Cur->Forward || !Cur->aliasesPointer(Ptr, Size, AAInfo, AA)) continue;
-     
--    if (!FoundSet) {      // If this is the first alias set ptr can go into.
--      FoundSet = Cur;     // Remember it.
-+    if (!FoundSet) {        // If this is the first alias set ptr can go into.
-+      FoundSet = &(*Cur);   // Remember it.
-     } else {              // Otherwise, we must merge the sets.
-       FoundSet->mergeSetIn(*Cur, *this);     // Merge in contents.
-     }
-@@ -264,16 +264,13 @@
-     if (Cur->Forward || !Cur->aliasesUnknownInst(Inst, AA))
-       continue;
-     if (!FoundSet)            // If this is the first alias set ptr can go into.
--      FoundSet = Cur;         // Remember it.
-+      FoundSet = &(*Cur);     // Remember it.
-     else if (!Cur->Forward)   // Otherwise, we must merge the sets.
-       FoundSet->mergeSetIn(*Cur, *this);     // Merge in contents.
-   }
-   return FoundSet;
- }
- 
--
--
--
- /// getAliasSetForPointer - Return the alias set that the specified pointer
- /// lives in.
- AliasSet &AliasSetTracker::getAliasSetForPointer(Value *Pointer, uint64_t Size,
-@@ -287,13 +284,13 @@
-     // Return the set!
-     return *Entry.getAliasSet(*this)->getForwardedTarget(*this);
-   }
--  
-+
-   if (AliasSet *AS = findAliasSetForPointer(Pointer, Size, AAInfo)) {
-     // Add it to the alias set it aliases.
-     AS->addPointer(*this, Entry, Size, AAInfo);
-     return *AS;
-   }
--  
-+
-   if (New) *New = true;
-   // Otherwise create a new alias set to hold the loaded pointer.
-   AliasSets.push_back(new AliasSet());
-@@ -379,8 +376,8 @@
- }
- 
- void AliasSetTracker::add(BasicBlock &BB) {
--  for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
--    add(I);
-+  for (auto &I : BB)
-+    add(&I);
- }
- 
- void AliasSetTracker::add(const AliasSetTracker &AST) {
---- lib/Analysis/BasicAliasAnalysis.cpp	2015-01-04 04:03:27.000000000 -0800
-+++ lib/Analysis/BasicAliasAnalysis.cpp	2015-11-27 09:53:17.612141117 -0800
-@@ -1440,7 +1440,7 @@
-   // the Values cannot come from different iterations of a potential cycle the
-   // phi nodes could be involved in.
-   for (auto *P : VisitedPhiBBs)
--    if (isPotentiallyReachable(P->begin(), Inst, DT, LI))
-+    if (isPotentiallyReachable(&P->front(), Inst, DT, LI))
-       return false;
- 
-   return true;
---- lib/Analysis/BlockFrequencyInfo.cpp	2014-06-26 15:52:05.000000000 -0700
-+++ lib/Analysis/BlockFrequencyInfo.cpp	2015-11-27 09:55:32.251496178 -0800
-@@ -34,17 +34,17 @@
- };
- 
- static cl::opt<GVDAGType>
--ViewBlockFreqPropagationDAG("view-block-freq-propagation-dags", cl::Hidden,
--          cl::desc("Pop up a window to show a dag displaying how block "
--                   "frequencies propagation through the CFG."),
--          cl::values(
--            clEnumValN(GVDT_None, "none",
--                       "do not display graphs."),
--            clEnumValN(GVDT_Fraction, "fraction", "display a graph using the "
--                       "fractional block frequency representation."),
--            clEnumValN(GVDT_Integer, "integer", "display a graph using the raw "
--                       "integer fractional block frequency representation."),
--            clEnumValEnd));
-+ViewBlockFreqPropagationDAG("view-block-freq-propagation-dags",
-+                            cl::Hidden,
-+                            cl::desc("Pop up a window to show a dag displaying how block "
-+                                     "frequencies propagation through the CFG."),
-+                            cl::values(clEnumValN(GVDT_None, "none",
-+                                                  "do not display graphs."),
-+                                       clEnumValN(GVDT_Fraction, "fraction", "display a graph using the "
-+                                                  "fractional block frequency representation."),
-+                                       clEnumValN(GVDT_Integer, "integer", "display a graph using the raw "
-+                                                  "integer fractional block frequency representation."),
-+                                       clEnumValEnd));
- 
- namespace llvm {
- 
-@@ -55,8 +55,9 @@
-   typedef Function::const_iterator nodes_iterator;
- 
-   static inline const NodeType *getEntryNode(const BlockFrequencyInfo *G) {
--    return G->getFunction()->begin();
-+    return &(G->getFunction()->front());
-   }
-+
-   static ChildIteratorType child_begin(const NodeType *N) {
-     return succ_begin(N);
-   }
---- lib/Analysis/BranchProbabilityInfo.cpp	2014-12-09 10:38:53.000000000 -0800
-+++ lib/Analysis/BranchProbabilityInfo.cpp	2015-11-27 09:59:58.010012465 -0800
-@@ -529,11 +529,10 @@
-   // We print the probabilities from the last function the analysis ran over,
-   // or the function it is currently running over.
-   assert(LastF && "Cannot print prior to running over a function");
--  for (Function::const_iterator BI = LastF->begin(), BE = LastF->end();
--       BI != BE; ++BI) {
--    for (succ_const_iterator SI = succ_begin(BI), SE = succ_end(BI);
-+  for (const auto &BI : *LastF) {
-+    for (succ_const_iterator SI = succ_begin(&BI), SE = succ_end(&BI);
-          SI != SE; ++SI) {
--      printEdgeProbability(OS << "  ", BI, *SI);
-+      printEdgeProbability(OS << "  ", &BI, *SI);
-     }
-   }
- }
---- lib/Analysis/CFG.cpp	2015-01-12 19:46:47.000000000 -0800
-+++ lib/Analysis/CFG.cpp	2015-11-27 10:13:16.659243122 -0800
-@@ -204,8 +204,9 @@
-       return true;
- 
-     // Linear scan, start at 'A', see whether we hit 'B' or the end first.
--    for (BasicBlock::const_iterator I = A, E = BB->end(); I != E; ++I) {
--      if (&*I == B)
-+    for (BasicBlock::const_iterator I = A->getIterator(), E = BB->end();
-+         I != E; ++I) {
-+      if (&(*I) == B)
-         return true;
-     }
- 
---- lib/Analysis/CodeMetrics.cpp	2015-01-04 04:03:27.000000000 -0800
-+++ lib/Analysis/CodeMetrics.cpp	2015-11-27 10:14:02.544976823 -0800
-@@ -115,7 +115,7 @@
-   for (BasicBlock::const_iterator II = BB->begin(), E = BB->end();
-        II != E; ++II) {
-     // Skip ephemeral values.
--    if (EphValues.count(II))
-+    if (EphValues.count(&(*II)))
-       continue;
- 
-     // Special handling for calls.
---- lib/Analysis/CostModel.cpp	2014-07-03 15:24:18.000000000 -0700
-+++ lib/Analysis/CostModel.cpp	2015-11-27 10:20:35.600601500 -0800
-@@ -524,7 +524,7 @@
- 
-   for (Function::iterator B = F->begin(), BE = F->end(); B != BE; ++B) {
-     for (BasicBlock::iterator it = B->begin(), e = B->end(); it != e; ++it) {
--      Instruction *Inst = it;
-+      Instruction *Inst = &(*it);
-       unsigned Cost = getInstructionCost(Inst);
-       if (Cost != (unsigned)-1)
-         OS << "Cost Model: Found an estimated cost of " << Cost;
---- lib/Analysis/IPA/CallGraph.cpp	2014-08-07 13:41:17.000000000 -0700
-+++ lib/Analysis/IPA/CallGraph.cpp	2015-11-27 17:17:06.153920405 -0800
-@@ -25,7 +25,7 @@
-       CallsExternalNode(new CallGraphNode(nullptr)) {
-   // Add every function to the call graph.
-   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
--    addToCallGraph(I);
-+    addToCallGraph(&*I);
- 
-   // If we didn't find a main function, use the external call graph node
-   if (!Root)
---- lib/Analysis/IPA/GlobalsModRef.cpp	2014-05-08 10:57:50.000000000 -0700
-+++ lib/Analysis/IPA/GlobalsModRef.cpp	2015-11-27 17:21:08.993461915 -0800
-@@ -209,9 +209,9 @@
-   std::vector<Function*> Readers, Writers;
-   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
-     if (I->hasLocalLinkage()) {
--      if (!AnalyzeUsesOfPointer(I, Readers, Writers)) {
-+      if (!AnalyzeUsesOfPointer(&*I, Readers, Writers)) {
-         // Remember that we are tracking this global.
--        NonAddressTakenGlobals.insert(I);
-+        NonAddressTakenGlobals.insert(&*I);
-         ++NumNonAddrTakenFunctions;
-       }
-       Readers.clear(); Writers.clear();
-@@ -220,24 +220,26 @@
-   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
-        I != E; ++I)
-     if (I->hasLocalLinkage()) {
--      if (!AnalyzeUsesOfPointer(I, Readers, Writers)) {
-+      if (!AnalyzeUsesOfPointer(&*I, Readers, Writers)) {
-         // Remember that we are tracking this global, and the mod/ref fns
--        NonAddressTakenGlobals.insert(I);
-+        NonAddressTakenGlobals.insert(&*I);
- 
-         for (unsigned i = 0, e = Readers.size(); i != e; ++i)
--          FunctionInfo[Readers[i]].GlobalInfo[I] |= Ref;
-+          FunctionInfo[Readers[i]].GlobalInfo[&*I] |= Ref;
- 
-         if (!I->isConstant())  // No need to keep track of writers to constants
-           for (unsigned i = 0, e = Writers.size(); i != e; ++i)
--            FunctionInfo[Writers[i]].GlobalInfo[I] |= Mod;
-+            FunctionInfo[Writers[i]].GlobalInfo[&*I] |= Mod;
-         ++NumNonAddrTakenGlobalVars;
- 
-         // If this global holds a pointer type, see if it is an indirect global.
-         if (I->getType()->getElementType()->isPointerTy() &&
--            AnalyzeIndirectGlobalMemory(I))
-+            AnalyzeIndirectGlobalMemory(&*I))
-           ++NumIndirectGlobalVars;
-       }
--      Readers.clear(); Writers.clear();
-+
-+      Readers.clear();
-+      Writers.clear();
-     }
- }
- 
---- lib/Analysis/IPA/InlineCost.cpp	2015-02-12 13:28:02.000000000 -0800
-+++ lib/Analysis/IPA/InlineCost.cpp	2015-11-27 17:25:16.116008808 -0800
-@@ -900,7 +900,7 @@
-       continue;
- 
-     // Skip ephemeral values.
--    if (EphValues.count(I))
-+    if (EphValues.count(&*I))
-       continue;
- 
-     ++NumInstructions;
-@@ -912,7 +912,7 @@
-     // all of the per-instruction logic. The visit tree returns true if we
-     // consumed the instruction in any way, and false if the instruction's base
-     // cost should count against inlining.
--    if (Base::visit(I))
-+    if (Base::visit(&*I))
-       ++NumInstructionsSimplified;
-     else
-       Cost += InlineConstants::InstrCost;
-@@ -1089,15 +1089,15 @@
-        FAI != FAE; ++FAI, ++CAI) {
-     assert(CAI != CS.arg_end());
-     if (Constant *C = dyn_cast<Constant>(CAI))
--      SimplifiedValues[FAI] = C;
-+      SimplifiedValues[&*FAI] = C;
- 
-     Value *PtrArg = *CAI;
-     if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) {
--      ConstantOffsetPtrs[FAI] = std::make_pair(PtrArg, C->getValue());
-+      ConstantOffsetPtrs[&*FAI] = std::make_pair(PtrArg, C->getValue());
- 
-       // We can SROA any pointer arguments derived from alloca instructions.
-       if (isa<AllocaInst>(PtrArg)) {
--        SROAArgValues[FAI] = PtrArg;
-+        SROAArgValues[&*FAI] = PtrArg;
-         SROAArgCosts[PtrArg] = 0;
-       }
-     }
-@@ -1334,9 +1334,8 @@
-     if (isa<IndirectBrInst>(BI->getTerminator()) || BI->hasAddressTaken())
-       return false;
- 
--    for (BasicBlock::iterator II = BI->begin(), IE = BI->end(); II != IE;
--         ++II) {
--      CallSite CS(II);
-+    for (auto &II : *BI) {
-+      CallSite CS(&II);
-       if (!CS)
-         continue;
- 
---- lib/Analysis/IVUsers.cpp	2014-11-18 23:49:26.000000000 -0800
-+++ lib/Analysis/IVUsers.cpp	2015-11-27 10:24:31.961529730 -0800
-@@ -248,7 +248,6 @@
- }
- 
- bool IVUsers::runOnLoop(Loop *l, LPPassManager &LPM) {
--
-   L = l;
-   LI = &getAnalysis<LoopInfo>();
-   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
-@@ -260,7 +259,7 @@
-   // them by stride.  Start by finding all of the PHI nodes in the header for
-   // this loop.  If they are induction variables, inspect their uses.
-   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
--    (void)AddUsersIfInteresting(I);
-+    (void) AddUsersIfInteresting(&(*I));
- 
-   return false;
- }
---- lib/Analysis/Lint.cpp	2015-01-04 04:03:27.000000000 -0800
-+++ lib/Analysis/Lint.cpp	2015-11-27 10:28:34.901567525 -0800
-@@ -231,7 +231,8 @@
-     for (; AI != AE; ++AI) {
-       Value *Actual = *AI;
-       if (PI != PE) {
--        Argument *Formal = PI++;
-+        Argument *Formal = &(*PI);
-+        PI++;
-         Assert1(Formal->getType() == Actual->getType(),
-                 "Undefined behavior: Call argument type mismatches "
-                 "callee parameter type", &I);
-@@ -609,8 +610,8 @@
- 
- void Lint::visitUnreachableInst(UnreachableInst &I) {
-   // This isn't undefined behavior, it's merely suspicious.
--  Assert1(&I == I.getParent()->begin() ||
--          std::prev(BasicBlock::iterator(&I))->mayHaveSideEffects(),
-+  Assert1(&I == &(I.getParent()->front()) ||
-+          std::prev(I.getIterator())->mayHaveSideEffects(),
-           "Unusual: unreachable immediately preceded by instruction without "
-           "side effects", &I);
- }
-@@ -641,7 +642,7 @@
-   // TODO: Look through vector insert/extract/shuffle.
-   V = OffsetOk ? GetUnderlyingObject(V, DL) : V->stripPointerCasts();
-   if (LoadInst *L = dyn_cast<LoadInst>(V)) {
--    BasicBlock::iterator BBI = L;
-+    BasicBlock::iterator BBI = L->getIterator();
-     BasicBlock *BB = L->getParent();
-     SmallPtrSet<BasicBlock *, 4> VisitedBlocks;
-     for (;;) {
---- lib/Analysis/Loads.cpp	2014-11-25 00:20:27.000000000 -0800
-+++ lib/Analysis/Loads.cpp	2015-11-27 17:11:12.096570890 -0800
-@@ -110,7 +110,8 @@
-   // from/to.  If so, the previous load or store would have already trapped,
-   // so there is no harm doing an extra load (also, CSE will later eliminate
-   // the load entirely).
--  BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
-+  BasicBlock::iterator BBI = ScanFrom->getIterator();
-+  BasicBlock::iterator E = ScanFrom->getParent()->begin();
- 
-   // We can at least always strip pointer casts even though we can't use the
-   // base here.
-@@ -189,7 +190,8 @@
-   while (ScanFrom != ScanBB->begin()) {
-     // We must ignore debug info directives when counting (otherwise they
-     // would affect codegen).
--    Instruction *Inst = --ScanFrom;
-+    --ScanFrom;
-+    Instruction *Inst = &(*ScanFrom);
-     if (isa<DbgInfoIntrinsic>(Inst))
-       continue;
- 
---- lib/Analysis/MemoryBuiltins.cpp	2014-11-18 23:49:26.000000000 -0800
-+++ lib/Analysis/MemoryBuiltins.cpp	2015-11-27 10:36:01.320964520 -0800
-@@ -642,7 +642,7 @@
- 
-   // always generate code immediately before the instruction being
-   // processed, so that the generated code dominates the same BBs
--  Instruction *PrevInsertPoint = Builder.GetInsertPoint();
-+  BuilderTy::InsertPointGuard Guard(Builder);
-   if (Instruction *I = dyn_cast<Instruction>(V))
-     Builder.SetInsertPoint(I);
- 
-@@ -671,9 +671,6 @@
-     Result = unknown();
-   }
- 
--  if (PrevInsertPoint)
--    Builder.SetInsertPoint(PrevInsertPoint);
--
-   // Don't reuse CacheIt since it may be invalid at this point.
-   CacheMap[V] = Result;
-   return Result;
-@@ -763,7 +760,7 @@
- 
-   // compute offset/size for each PHI incoming pointer
-   for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
--    Builder.SetInsertPoint(PHI.getIncomingBlock(i)->getFirstInsertionPt());
-+    Builder.SetInsertPoint(&*PHI.getIncomingBlock(i)->getFirstInsertionPt());
-     SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
- 
-     if (!bothKnown(EdgeData)) {
---- lib/Analysis/MemoryDependenceAnalysis.cpp	2015-01-08 16:26:45.000000000 -0800
-+++ lib/Analysis/MemoryDependenceAnalysis.cpp	2015-11-27 17:13:54.649752810 -0800
-@@ -215,7 +215,8 @@
-     if (!Limit)
-       return MemDepResult::getUnknown();
- 
--    Instruction *Inst = --ScanIt;
-+    --ScanIt;
-+    Instruction *Inst = &(*ScanIt);
- 
-     // If this inst is a memory op, get the pointer it accessed
-     AliasAnalysis::Location Loc;
-@@ -415,7 +416,8 @@
- 
-   // Walk backwards through the basic block, looking for dependencies.
-   while (ScanIt != BB->begin()) {
--    Instruction *Inst = --ScanIt;
-+    --ScanIt;
-+    Instruction *Inst = &(*ScanIt);
- 
-     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
-       // Debug intrinsics don't (and can't) cause dependencies.
-@@ -676,12 +678,14 @@
-       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(QueryInst))
-         isLoad |= II->getIntrinsicID() == Intrinsic::lifetime_start;
- 
--      LocalCache = getPointerDependencyFrom(MemLoc, isLoad, ScanPos,
-+      LocalCache = getPointerDependencyFrom(MemLoc, isLoad,
-+                                            ScanPos->getIterator(),
-                                             QueryParent, QueryInst);
-     } else if (isa<CallInst>(QueryInst) || isa<InvokeInst>(QueryInst)) {
-       CallSite QueryCS(QueryInst);
-       bool isReadOnly = AA->onlyReadsMemory(QueryCS);
--      LocalCache = getCallSiteDependencyFrom(QueryCS, isReadOnly, ScanPos,
-+      LocalCache = getCallSiteDependencyFrom(QueryCS, isReadOnly,
-+                                             ScanPos->getIterator(),
-                                              QueryParent);
-     } else
-       // Non-memory instruction.
-@@ -805,7 +809,7 @@
-     BasicBlock::iterator ScanPos = DirtyBB->end();
-     if (ExistingResult) {
-       if (Instruction *Inst = ExistingResult->getResult().getInst()) {
--        ScanPos = Inst;
-+        ScanPos = Inst->getIterator();
-         // We're removing QueryInst's use of Inst.
-         RemoveFromReverseMap(ReverseNonLocalDeps, Inst,
-                              QueryCS.getInstruction());
-@@ -969,11 +973,11 @@
-     assert(ExistingResult->getResult().getInst()->getParent() == BB &&
-            "Instruction invalidated?");
-     ++NumCacheDirtyNonLocalPtr;
--    ScanPos = ExistingResult->getResult().getInst();
-+    ScanPos = ExistingResult->getResult().getInst()->getIterator();
- 
-     // Eliminating the dirty entry from 'Cache', so update the reverse info.
-     ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
--    RemoveFromReverseMap(ReverseNonLocalPtrDeps, ScanPos, CacheKey);
-+    RemoveFromReverseMap(ReverseNonLocalPtrDeps, &(*ScanPos), CacheKey);
-   } else {
-     ++NumUncacheNonLocalPtr;
-   }
-@@ -1524,8 +1528,10 @@
-   // Using a dirty version of the instruction after RemInst saves having to scan
-   // the entire block to get to this point.
-   MemDepResult NewDirtyVal;
--  if (!RemInst->isTerminator())
--    NewDirtyVal = MemDepResult::getDirty(++BasicBlock::iterator(RemInst));
-+  if (!RemInst->isTerminator()) {
-+    ++RemInst;
-+    NewDirtyVal = MemDepResult::getDirty(&*RemInst->getIterator());
-+  }
- 
-   ReverseDepMapType::iterator ReverseDepIt = ReverseLocalDeps.find(RemInst);
-   if (ReverseDepIt != ReverseLocalDeps.end()) {
---- lib/Analysis/ScalarEvolutionExpander.cpp	2015-03-16 14:15:49.000000000 -0700
-+++ lib/Analysis/ScalarEvolutionExpander.cpp	2015-11-27 17:14:51.881419145 -0800
-@@ -59,7 +59,7 @@
-             // Create a new cast, and leave the old cast in place in case
-             // it is being used as an insert point. Clear its operand
-             // so that it doesn't hold anything live.
--            Ret = CastInst::Create(Op, V, Ty, "", IP);
-+            Ret = CastInst::Create(Op, V, Ty, "", &(*IP));
-             Ret->takeName(CI);
-             CI->replaceAllUsesWith(Ret);
-             CI->setOperand(0, UndefValue::get(V->getType()));
-@@ -71,12 +71,12 @@
- 
-   // Create a new cast.
-   if (!Ret)
--    Ret = CastInst::Create(Op, V, Ty, V->getName(), IP);
-+    Ret = CastInst::Create(Op, V, Ty, V->getName(), &(*IP));
- 
-   // We assert at the end of the function since IP might point to an
-   // instruction with different dominance properties than a cast
-   // (an invoke for example) and not dominate BIP (but the cast does).
--  assert(SE.DT->dominates(Ret, BIP));
-+  assert(SE.DT->dominates(Ret, &(*BIP)));
- 
-   rememberInstruction(Ret);
-   return Ret;
-@@ -139,7 +139,8 @@
- 
-   // Cast the instruction immediately after the instruction.
-   Instruction *I = cast<Instruction>(V);
--  BasicBlock::iterator IP = I; ++IP;
-+  ++I;
-+  BasicBlock::iterator IP = I->getIterator();
-   if (InvokeInst *II = dyn_cast<InvokeInst>(I))
-     IP = II->getNormalDest()->begin();
-   while (isa<PHINode>(IP) || isa<LandingPadInst>(IP))
-@@ -170,7 +171,7 @@
-         ScanLimit++;
-       if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
-           IP->getOperand(1) == RHS)
--        return IP;
-+        return &(*IP);
-       if (IP == BlockBegin) break;
-     }
-   }
-@@ -186,7 +187,7 @@
-     if (!Preheader) break;
- 
-     // Ok, move up a level.
--    Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
-+    Builder.SetInsertPoint(Preheader->getTerminator());
-   }
- 
-   // If we haven't found this binop, insert it.
-@@ -518,7 +519,8 @@
-        Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
- 
-     assert(!isa<Instruction>(V) ||
--           SE.DT->dominates(cast<Instruction>(V), Builder.GetInsertPoint()));
-+           SE.DT->dominates(cast<Instruction>(V),
-+                            &(*Builder.GetInsertPoint())));
- 
-     // Expand the operands for a plain byte offset.
-     Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
-@@ -542,7 +544,7 @@
-           ScanLimit++;
-         if (IP->getOpcode() == Instruction::GetElementPtr &&
-             IP->getOperand(0) == V && IP->getOperand(1) == Idx)
--          return IP;
-+          return &(*IP);
-         if (IP == BlockBegin) break;
-       }
-     }
-@@ -557,7 +559,7 @@
-       if (!Preheader) break;
- 
-       // Ok, move up a level.
--      Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
-+      Builder.SetInsertPoint(Preheader->getTerminator());
-     }
- 
-     // Emit a GEP.
-@@ -588,7 +590,7 @@
-     if (!Preheader) break;
- 
-     // Ok, move up a level.
--    Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
-+    Builder.SetInsertPoint(Preheader->getTerminator());
-   }
- 
-   // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
-@@ -1168,8 +1170,8 @@
-   PostIncLoops.clear();
- 
-   // Expand code for the start value.
--  Value *StartV = expandCodeFor(Normalized->getStart(), ExpandTy,
--                                L->getHeader()->begin());
-+  Value *StartV =
-+    expandCodeFor(Normalized->getStart(), ExpandTy, &(L->getHeader()->front()));
- 
-   // StartV must be hoisted into L's preheader to dominate the new phi.
-   assert(!isa<Instruction>(StartV) ||
-@@ -1186,7 +1188,7 @@
-   if (useSubtract)
-     Step = SE.getNegativeSCEV(Step);
-   // Expand the step somewhere that dominates the loop header.
--  Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
-+  Value *StepV = expandCodeFor(Step, IntTy, &(L->getHeader()->front()));
- 
-   // Create the PHI.
-   BasicBlock *Header = L->getHeader();
-@@ -1297,7 +1299,7 @@
-     // or dominated by IVIncInsertPos.
-     if (isa<Instruction>(Result)
-         && !SE.DT->dominates(cast<Instruction>(Result),
--                             Builder.GetInsertPoint())) {
-+                             &(*Builder.GetInsertPoint()))) {
-       // The induction variable's postinc expansion does not dominate this use.
-       // IVUsers tries to prevent this case, so it is rare. However, it can
-       // happen when an IVUser outside the loop is not dominated by the latch
-@@ -1315,8 +1317,9 @@
-       {
-         // Expand the step somewhere that dominates the loop header.
-         BuilderType::InsertPointGuard Guard(Builder);
--        StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
-+        StepV = expandCodeFor(Step, IntTy, &(L->getHeader()->front()));
-       }
-+
-       Result = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
-     }
-   }
-@@ -1395,7 +1398,7 @@
-            isa<LandingPadInst>(NewInsertPt))
-       ++NewInsertPt;
-     V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), nullptr,
--                      NewInsertPt);
-+                      &(*NewInsertPt));
-     return V;
-   }
- 
-@@ -1436,7 +1439,7 @@
-     BasicBlock *Header = L->getHeader();
-     pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
-     CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar",
--                                  Header->begin());
-+                                  &(Header->front()));
-     rememberInstruction(CanonicalIV);
- 
-     SmallSet<BasicBlock *, 4> PredSeen;
-@@ -1581,7 +1584,8 @@
- 
- Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty,
-                                    Instruction *IP) {
--  Builder.SetInsertPoint(IP->getParent(), IP);
-+  assert(IP && "Invalid Instruction argument!");
-+  Builder.SetInsertPoint(IP);
-   return expandCodeFor(SH, Ty);
- }
- 
-@@ -1599,7 +1603,7 @@
- Value *SCEVExpander::expand(const SCEV *S) {
-   // Compute an insertion point for this SCEV object. Hoist the instructions
-   // as far out in the loop nest as possible.
--  Instruction *InsertPt = Builder.GetInsertPoint();
-+  Instruction *InsertPt = &(*Builder.GetInsertPoint());
-   for (Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock()); ;
-        L = L->getParentLoop())
-     if (SE.isLoopInvariant(S, L)) {
-@@ -1610,18 +1614,18 @@
-         // LSR sets the insertion point for AddRec start/step values to the
-         // block start to simplify value reuse, even though it's an invalid
-         // position. SCEVExpander must correct for this in all cases.
--        InsertPt = L->getHeader()->getFirstInsertionPt();
-+        InsertPt = &*L->getHeader()->getFirstInsertionPt();
-       }
-     } else {
-       // If the SCEV is computable at this level, insert it into the header
-       // after the PHIs (and after any other instructions that we've inserted
-       // there) so that it is guaranteed to dominate any user inside the loop.
-       if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
--        InsertPt = L->getHeader()->getFirstInsertionPt();
-+        InsertPt = &*L->getHeader()->getFirstInsertionPt();
-       while (InsertPt != Builder.GetInsertPoint()
-              && (isInsertedInstruction(InsertPt)
-                  || isa<DbgInfoIntrinsic>(InsertPt))) {
--        InsertPt = std::next(BasicBlock::iterator(InsertPt));
-+        InsertPt = &(*std::next(BasicBlock::iterator(InsertPt)));
-       }
-       break;
-     }
-@@ -1633,7 +1637,7 @@
-     return I->second;
- 
-   BuilderType::InsertPointGuard Guard(Builder);
--  Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
-+  Builder.SetInsertPoint(InsertPt);
- 
-   // Expand the expression into instructions.
-   Value *V = visit(S);
-@@ -1671,8 +1675,9 @@
- 
-   // Emit code for it.
-   BuilderType::InsertPointGuard Guard(Builder);
--  PHINode *V = cast<PHINode>(expandCodeFor(H, nullptr,
--                                           L->getHeader()->begin()));
-+  PHINode *V =
-+    cast<PHINode>(expandCodeFor(H, nullptr,
-+                                &(L->getHeader()->front())));
- 
-   return V;
- }
-@@ -1778,7 +1783,7 @@
-         if (OrigInc->getType() != IsomorphicInc->getType()) {
-           Instruction *IP = nullptr;
-           if (PHINode *PN = dyn_cast<PHINode>(OrigInc))
--            IP = PN->getParent()->getFirstInsertionPt();
-+            IP = &*PN->getParent()->getFirstInsertionPt();
-           else
-             IP = OrigInc->getNextNode();
- 
-@@ -1796,7 +1801,7 @@
-     ++NumElim;
-     Value *NewIV = OrigPhiRef;
-     if (OrigPhiRef->getType() != Phi->getType()) {
--      IRBuilder<> Builder(L->getHeader()->getFirstInsertionPt());
-+      IRBuilder<> Builder(&*L->getHeader()->getFirstInsertionPt());
-       Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
-       NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName);
-     }
---- lib/Analysis/ScalarEvolutionNormalization.cpp	2014-08-29 14:53:01.000000000 -0700
-+++ lib/Analysis/ScalarEvolutionNormalization.cpp	2015-11-27 15:32:52.251292445 -0800
-@@ -109,7 +109,7 @@
-     SmallVector<const SCEV *, 8> Operands;
-     const Loop *L = AR->getLoop();
-     // The addrec conceptually uses its operands at loop entry.
--    Instruction *LUser = L->getHeader()->begin();
-+    Instruction *LUser = &(L->getHeader()->front());
-     // Transform each operand.
-     for (SCEVNAryExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
-          I != E; ++I) {
---- lib/Analysis/SparsePropagation.cpp	2014-04-21 19:48:03.000000000 -0700
-+++ lib/Analysis/SparsePropagation.cpp	2015-11-27 16:56:54.595156233 -0800
-@@ -328,17 +328,17 @@
- 
- void SparseSolver::Print(Function &F, raw_ostream &OS) const {
-   OS << "\nFUNCTION: " << F.getName() << "\n";
--  for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
--    if (!BBExecutable.count(BB))
-+  for (auto &BB : F) {
-+    if (!BBExecutable.count(&BB))
-       OS << "INFEASIBLE: ";
-     OS << "\t";
--    if (BB->hasName())
--      OS << BB->getName() << ":\n";
-+    if (BB.hasName())
-+      OS << BB.getName() << ":\n";
-     else
-       OS << "; anon bb\n";
--    for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
--      LatticeFunc->PrintValue(getLatticeState(I), OS);
--      OS << *I << "\n";
-+    for (auto &I : BB) {
-+      LatticeFunc->PrintValue(getLatticeState(&I), OS);
-+      OS << I << "\n";
-     }
-     
-     OS << "\n";
---- lib/Analysis/ValueTracking.cpp	2015-01-14 03:23:27.000000000 -0800
-+++ lib/Analysis/ValueTracking.cpp	2015-11-27 17:02:21.643435710 -0800
-@@ -403,8 +403,8 @@
-       for (BasicBlock::const_iterator I =
-              std::next(BasicBlock::const_iterator(Q.CxtI)),
-                                       IE(Inv); I != IE; ++I)
--        if (!isSafeToSpeculativelyExecute(I, DL) &&
--            !isAssumeLikeIntrinsic(I))
-+        if (!isSafeToSpeculativelyExecute(&*I, DL) &&
-+            !isAssumeLikeIntrinsic(&*I))
-           return false;
- 
-       return !isEphemeralValueOf(Inv, Q.CxtI);
-@@ -421,15 +421,15 @@
-     // of the block); the common case is that the assume will come first.
-     for (BasicBlock::iterator I = std::next(BasicBlock::iterator(Inv)),
-          IE = Inv->getParent()->end(); I != IE; ++I)
--      if (I == Q.CxtI)
-+      if (&*I == Q.CxtI)
-         return true;
- 
-     // The context must come first...
-     for (BasicBlock::const_iterator I =
-            std::next(BasicBlock::const_iterator(Q.CxtI)),
-                                     IE(Inv); I != IE; ++I)
--      if (!isSafeToSpeculativelyExecute(I, DL) &&
--          !isAssumeLikeIntrinsic(I))
-+      if (!isSafeToSpeculativelyExecute(&*I, DL) &&
-+          !isAssumeLikeIntrinsic(&*I))
-         return false;
- 
-     return !isEphemeralValueOf(Inv, Q.CxtI);
---- lib/AsmParser/LLParser.cpp	2015-01-13 13:10:44.000000000 -0800
-+++ lib/AsmParser/LLParser.cpp	2015-12-06 12:01:01.192696877 -0800
-@@ -152,8 +152,10 @@
-       U->resolveCycles();
- 
-   // Look for intrinsic functions and CallInst that need to be upgraded
--  for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
--    UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
-+  for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
-+    UpgradeCallsToIntrinsic(&*FI); // must be post-increment, as we remove
-+    ++FI;
-+  }
- 
-   UpgradeDebugInfo(*M);
- 
-@@ -2091,7 +2093,7 @@
-   for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
-        AI != E; ++AI)
-     if (!AI->hasName())
--      NumberedVals.push_back(AI);
-+      NumberedVals.push_back(&*AI);
- }
- 
- LLParser::PerFunctionState::~PerFunctionState() {
---- lib/Bitcode/Reader/BitcodeReader.cpp	2015-02-17 13:27:11.000000000 -0800
-+++ lib/Bitcode/Reader/BitcodeReader.cpp	2015-12-06 12:21:14.006297865 -0800
-@@ -1830,7 +1830,7 @@
-             return Error("Invalid ID");
-           ++BBI;
-         }
--        BB = BBI;
-+        BB = &*BBI;
-       } else {
-         // Otherwise insert a placeholder and remember it so it can be inserted
-         // when the function is parsed.
-@@ -1945,20 +1945,15 @@
-     return Error("Malformed global initializer set");
- 
-   // Look for intrinsic functions which need to be upgraded at some point
--  for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
--       FI != FE; ++FI) {
-+  for (Function &F : *TheModule) {
-     Function *NewFn;
--    if (UpgradeIntrinsicFunction(FI, NewFn))
--      UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
-+    if (UpgradeIntrinsicFunction(&F, NewFn))
-+      UpgradedIntrinsics.push_back(std::make_pair(&F, NewFn));
-   }
- 
-   // Look for global variables which need to be renamed.
--  for (Module::global_iterator
--         GI = TheModule->global_begin(), GE = TheModule->global_end();
--       GI != GE;) {
--    GlobalVariable *GV = GI++;
--    UpgradeGlobalVariable(GV);
--  }
-+  for (GlobalVariable &GV : TheModule->globals())
-+    UpgradeGlobalVariable(&GV);
- 
-   // Force deallocation of memory for these vectors to favor the client that
-   // want lazy deserialization.
-@@ -2528,8 +2523,8 @@
-   unsigned ModuleMDValueListSize = MDValueList.size();
- 
-   // Add all the function arguments to the value table.
--  for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
--    ValueList.push_back(I);
-+  for (Argument &I : F->args())
-+    ValueList.push_back(&I);
- 
-   unsigned NextValueNo = ValueList.size();
-   BasicBlock *CurBB = nullptr;
-@@ -3555,9 +3550,8 @@
- 
-   // Iterate over the module, deserializing any functions that are still on
-   // disk.
--  for (Module::iterator F = TheModule->begin(), E = TheModule->end();
--       F != E; ++F) {
--    if (std::error_code EC = materialize(F))
-+  for (Function &F : *TheModule) {
-+    if (std::error_code EC = materialize(&F))
-       return EC;
-   }
-   // At this point, if there are any function bodies, the current bit is
---- lib/Bitcode/Writer/BitcodeWriter.cpp	2015-01-13 13:10:44.000000000 -0800
-+++ lib/Bitcode/Writer/BitcodeWriter.cpp	2015-12-06 12:22:42.877667625 -0800
-@@ -924,7 +924,7 @@
-       // If no metadata, ignore instruction.
-       if (MDs.empty()) continue;
- 
--      Record.push_back(VE.getInstructionID(I));
-+      Record.push_back(VE.getInstructionID(&*I));
- 
-       for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
-         Record.push_back(MDs[i].first);
---- lib/Bitcode/Writer/ValueEnumerator.cpp	2015-01-13 13:10:44.000000000 -0800
-+++ lib/Bitcode/Writer/ValueEnumerator.cpp	2015-12-06 12:26:51.090576745 -0800
-@@ -290,18 +290,18 @@
-   // Enumerate the global variables.
-   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
-        I != E; ++I)
--    EnumerateValue(I);
-+    EnumerateValue(&*I);
- 
-   // Enumerate the functions.
-   for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
--    EnumerateValue(I);
-+    EnumerateValue(&*I);
-     EnumerateAttributes(cast<Function>(I)->getAttributes());
-   }
- 
-   // Enumerate the aliases.
-   for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
-        I != E; ++I)
--    EnumerateValue(I);
-+    EnumerateValue(&*I);
- 
-   // Remember what is the cutoff between globalvalue's and other constants.
-   unsigned FirstConstant = Values.size();
-@@ -509,7 +509,7 @@
-   for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
-                                              E = M.named_metadata_end();
-        I != E; ++I)
--    EnumerateNamedMDNode(I);
-+    EnumerateNamedMDNode(&*I);
- }
- 
- void ValueEnumerator::EnumerateNamedMDNode(const NamedMDNode *MD) {
-@@ -726,7 +726,7 @@
-   // Adding function arguments to the value table.
-   for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
-        I != E; ++I)
--    EnumerateValue(I);
-+    EnumerateValue(&*I);
- 
-   FirstFuncConstantID = Values.size();
- 
-@@ -739,8 +739,8 @@
-             isa<InlineAsm>(*OI))
-           EnumerateValue(*OI);
-       }
--    BasicBlocks.push_back(BB);
--    ValueMap[BB] = BasicBlocks.size();
-+    BasicBlocks.push_back(&*BB);
-+    ValueMap[&*BB] = BasicBlocks.size();
-   }
- 
-   // Optimize the constant layout.
-@@ -765,7 +765,7 @@
-       }
- 
-       if (!I->getType()->isVoidTy())
--        EnumerateValue(I);
-+        EnumerateValue(&*I);
-     }
-   }
- 
-@@ -793,7 +793,7 @@
-                                  DenseMap<const BasicBlock*, unsigned> &IDMap) {
-   unsigned Counter = 0;
-   for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
--    IDMap[BB] = ++Counter;
-+    IDMap[&*BB] = ++Counter;
- }
- 
- /// getGlobalBasicBlockID - This returns the function-specific ID for the
---- lib/CodeGen/Analysis.cpp	2015-06-12 08:57:35.000000000 -0700
-+++ lib/CodeGen/Analysis.cpp	2015-12-06 12:38:15.443685028 -0800
-@@ -514,7 +514,7 @@
-       if (isa<DbgInfoIntrinsic>(BBI))
-         continue;
-       if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
--          !isSafeToSpeculativelyExecute(BBI))
-+          !isSafeToSpeculativelyExecute(&*BBI))
-         return false;
-     }
- 
---- lib/CodeGen/AsmPrinter/AsmPrinter.cpp	2015-01-12 16:48:10.000000000 -0800
-+++ lib/CodeGen/AsmPrinter/AsmPrinter.cpp	2016-01-21 10:23:14.978051692 -0800
-@@ -857,6 +857,7 @@
-     MCSymbol *Sym = GetBlockAddressSymbol(&BB);
-     if (Sym->isDefined())
-       continue;
-+
-     OutStreamer.AddComment("Address of block that was removed by CodeGen");
-     OutStreamer.EmitLabel(Sym);
-   }
-@@ -864,8 +865,8 @@
-   // Emit target-specific gunk after the function body.
-   EmitFunctionBodyEnd();
- 
--  // If the target wants a .size directive for the size of the function, emit
--  // it.
-+  // If the target wants a .size directive for the size of the function,
-+  // emit it.
-   if (MAI->hasDotTypeDotSizeDirective()) {
-     // Create a symbol for the end of function, so we can get the size as
-     // difference between the function label and the temp label.
-@@ -885,6 +886,7 @@
-     NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
-     HI.Handler->endFunction(MF);
-   }
-+
-   MMI->EndFunction();
- 
-   // Print out jump tables referenced by the function.
---- lib/CodeGen/AtomicExpandPass.cpp	2014-09-25 10:27:43.000000000 -0700
-+++ lib/CodeGen/AtomicExpandPass.cpp	2015-12-06 12:41:26.021558967 -0800
-@@ -298,7 +298,8 @@
-   // atomicrmw.end:
-   //     fence?
-   //     [...]
--  BasicBlock *ExitBB = BB->splitBasicBlock(AI, "atomicrmw.end");
-+  BasicBlock *ExitBB = BB->splitBasicBlock(AI->getIterator(),
-+                                           "atomicrmw.end");
-   BasicBlock *LoopBB =  BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
- 
-   // This grabs the DebugLoc from AI.
-@@ -355,7 +356,7 @@
-   //     br i1 %success, label %atomicrmw.end, label %loop
-   // atomicrmw.end:
-   //     [...]
--  BasicBlock *ExitBB = BB->splitBasicBlock(AI, "atomicrmw.end");
-+  BasicBlock *ExitBB = BB->splitBasicBlock(AI->getIterator(), "atomicrmw.end");
-   BasicBlock *LoopBB = BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
- 
-   // This grabs the DebugLoc from AI.
-@@ -436,7 +437,7 @@
-   //     %restmp = insertvalue { iN, i1 } undef, iN %loaded, 0
-   //     %res = insertvalue { iN, i1 } %restmp, i1 %success, 1
-   //     [...]
--  BasicBlock *ExitBB = BB->splitBasicBlock(CI, "cmpxchg.end");
-+  BasicBlock *ExitBB = BB->splitBasicBlock(CI->getIterator(), "cmpxchg.end");
-   auto FailureBB = BasicBlock::Create(Ctx, "cmpxchg.failure", F, ExitBB);
-   auto SuccessBB = BasicBlock::Create(Ctx, "cmpxchg.success", F, FailureBB);
-   auto TryStoreBB = BasicBlock::Create(Ctx, "cmpxchg.trystore", F, SuccessBB);
---- lib/CodeGen/BasicTargetTransformInfo.cpp	2015-01-07 16:51:32.000000000 -0800
-+++ lib/CodeGen/BasicTargetTransformInfo.cpp	2015-12-06 12:42:25.950965490 -0800
-@@ -240,7 +240,7 @@
- 
-     for (BasicBlock::iterator J = BB->begin(), JE = BB->end(); J != JE; ++J)
-       if (isa<CallInst>(J) || isa<InvokeInst>(J)) {
--        ImmutableCallSite CS(J);
-+        ImmutableCallSite CS(&*J);
-         if (const Function *F = CS.getCalledFunction()) {
-           if (!TopTTI->isLoweredToCall(F))
-             continue;
---- lib/CodeGen/BranchFolding.cpp	2014-11-18 23:49:26.000000000 -0800
-+++ lib/CodeGen/BranchFolding.cpp	2015-12-06 14:41:40.491854005 -0800
-@@ -130,7 +130,7 @@
-   TriedMerging.erase(MBB);
- 
-   // Remove the block.
--  MF->erase(MBB);
-+  MF->erase(MBB->getIterator());
- }
- 
- /// OptimizeImpDefsBlock - If a basic block is just a bunch of implicit_def
-@@ -207,12 +207,12 @@
- 
-   // Fix CFG.  The later algorithms expect it to be right.
-   bool MadeChange = false;
--  for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; I++) {
--    MachineBasicBlock *MBB = I, *TBB = nullptr, *FBB = nullptr;
-+  for (MachineBasicBlock &MBB : MF) {
-+    MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
-     SmallVector<MachineOperand, 4> Cond;
--    if (!TII->AnalyzeBranch(*MBB, TBB, FBB, Cond, true))
--      MadeChange |= MBB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
--    MadeChange |= OptimizeImpDefsBlock(MBB);
-+    if (!TII->AnalyzeBranch(MBB, TBB, FBB, Cond, true))
-+      MadeChange |= MBB.CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
-+    MadeChange |= OptimizeImpDefsBlock(&MBB);
-   }
- 
-   bool MadeChangeThisIteration = true;
-@@ -426,7 +426,7 @@
-   MachineFunction &MF = *CurMBB.getParent();
- 
-   // Create the fall-through block.
--  MachineFunction::iterator MBBI = &CurMBB;
-+  MachineFunction::iterator MBBI = CurMBB.getIterator();
-   MachineBasicBlock *NewMBB =MF.CreateMachineBasicBlock(BB);
-   CurMBB.getParent()->insert(++MBBI, NewMBB);
- 
-@@ -479,7 +479,7 @@
-   DebugLoc dl;  // FIXME: this is nowhere
-   if (I != MF->end() &&
-       !TII->AnalyzeBranch(*CurMBB, TBB, FBB, Cond, true)) {
--    MachineBasicBlock *NextBB = I;
-+    MachineBasicBlock *NextBB = &*I;
-     if (TBB == NextBB && !Cond.empty() && !FBB) {
-       if (!TII->ReverseBranchCondition(Cond)) {
-         TII->RemoveBranch(*CurMBB);
-@@ -785,8 +785,8 @@
-     // block, which we can't jump to), we can treat all blocks with this same
-     // tail at once.  Use PredBB if that is one of the possibilities, as that
-     // will not introduce any extra branches.
--    MachineBasicBlock *EntryBB = MergePotentials.begin()->getBlock()->
--                                 getParent()->begin();
-+    MachineBasicBlock *EntryBB =
-+      &MergePotentials.front().getBlock()->getParent()->front();
-     unsigned commonTailIndex = SameTails.size();
-     // If there are two blocks, check to see if one can be made to fall through
-     // into the other.
-@@ -860,12 +860,12 @@
- 
-   // First find blocks with no successors.
-   MergePotentials.clear();
--  for (MachineFunction::iterator I = MF.begin(), E = MF.end();
--       I != E && MergePotentials.size() < TailMergeThreshold; ++I) {
--    if (TriedMerging.count(I))
--      continue;
--    if (I->succ_empty())
--      MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(I), I));
-+  for (MachineBasicBlock &MBB : MF) {
-+    if (MergePotentials.size() == TailMergeThreshold)
-+      break;
-+
-+    if (!TriedMerging.count(&MBB) && MBB.succ_empty())
-+      MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(&MBB), &MBB));
-   }
- 
-   // If this is a large problem, avoid visiting the same basic blocks
-@@ -901,8 +901,8 @@
-        I != E; ++I) {
-     if (I->pred_size() < 2) continue;
-     SmallPtrSet<MachineBasicBlock *, 8> UniquePreds;
--    MachineBasicBlock *IBB = I;
--    MachineBasicBlock *PredBB = std::prev(I);
-+    MachineBasicBlock *IBB = &*I;
-+    MachineBasicBlock *PredBB = &*std::prev(I);
-     MergePotentials.clear();
-     for (MachineBasicBlock::pred_iterator P = I->pred_begin(),
-            E2 = I->pred_end();
-@@ -933,18 +933,21 @@
-           if (TII->ReverseBranchCondition(NewCond))
-             continue;
-           // This is the QBB case described above
--          if (!FBB)
--            FBB = std::next(MachineFunction::iterator(PBB));
-+          if (!FBB) {
-+            auto Next = ++PBB->getIterator();
-+            if (Next != MF.end())
-+              FBB = &*Next;
-+          }
-         }
- 
-         // Failing case: the only way IBB can be reached from PBB is via
-         // exception handling.  Happens for landing pads.  Would be nice to have
-         // a bit in the edge so we didn't have to do all this.
-         if (IBB->isLandingPad()) {
--          MachineFunction::iterator IP = PBB;  IP++;
-+          MachineFunction::iterator IP = ++PBB->getIterator();
-           MachineBasicBlock *PredNextBB = nullptr;
-           if (IP != MF.end())
--            PredNextBB = IP;
-+            PredNextBB = &*IP;
-           if (!TBB) {
-             if (IBB != PredNextBB)      // fallthrough
-               continue;
-@@ -985,7 +988,7 @@
- 
-     // Reinsert an unconditional branch if needed. The 1 below can occur as a
-     // result of removing blocks in TryTailMergeBlocks.
--    PredBB = std::prev(I);     // this may have been changed in TryTailMergeBlocks
-+    PredBB = &*std::prev(I);     // this may have been changed in TryTailMergeBlocks
-     if (MergePotentials.size() == 1 &&
-         MergePotentials.begin()->getBlock() != PredBB)
-       FixTail(MergePotentials.begin()->getBlock(), IBB, TII);
-@@ -1044,7 +1047,7 @@
- 
-   for (MachineFunction::iterator I = std::next(MF.begin()), E = MF.end();
-        I != E; ) {
--    MachineBasicBlock *MBB = I++;
-+    MachineBasicBlock *MBB = &*I++;
-     MadeChange |= OptimizeBlock(MBB);
- 
-     // If it is dead, remove it.
-@@ -1132,7 +1135,7 @@
-   MachineFunction &MF = *MBB->getParent();
- ReoptimizeBlock:
- 
--  MachineFunction::iterator FallThrough = MBB;
-+  MachineFunction::iterator FallThrough = MBB->getIterator();
-   ++FallThrough;
- 
-   // If this block is empty, make everyone use its fall-through, not the block
-@@ -1150,12 +1153,12 @@
-       // instead.
-       while (!MBB->pred_empty()) {
-         MachineBasicBlock *Pred = *(MBB->pred_end()-1);
--        Pred->ReplaceUsesOfBlockWith(MBB, FallThrough);
-+        Pred->ReplaceUsesOfBlockWith(MBB, &*FallThrough);
-       }
-       // If MBB was the target of a jump table, update jump tables to go to the
-       // fallthrough instead.
-       if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
--        MJTI->ReplaceMBBInJumpTables(MBB, FallThrough);
-+        MJTI->ReplaceMBBInJumpTables(MBB, &*FallThrough);
-       MadeChange = true;
-     }
-     return MadeChange;
-@@ -1293,7 +1296,7 @@
-           TII->InsertBranch(PrevBB, MBB, nullptr, NewPriorCond, dl);
- 
-           // Move this block to the end of the function.
--          MBB->moveAfter(--MF.end());
-+          MBB->moveAfter(&MF.back());
-           MadeChange = true;
-           ++NumBranchOpts;
-           return MadeChange;
-@@ -1440,11 +1443,8 @@
-     if (!MBB->isLandingPad()) {
-       // Check all the predecessors of this block.  If one of them has no fall
-       // throughs, move this block right after it.
--      for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
--           E = MBB->pred_end(); PI != E; ++PI) {
-+      for (MachineBasicBlock *PredBB : MBB->predecessors()) {
-         // Analyze the branch at the end of the pred.
--        MachineBasicBlock *PredBB = *PI;
--        MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
-         MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
-         SmallVector<MachineOperand, 4> PredCond;
-         if (PredBB != MBB && !PredBB->canFallThrough() &&
-@@ -1462,8 +1462,7 @@
-           // B elsewhere
-           // next:
-           if (CurFallsThru) {
--            MachineBasicBlock *NextBB =
--                std::next(MachineFunction::iterator(MBB));
-+            MachineBasicBlock *NextBB = &*std::next(MBB->getIterator());
-             CurCond.clear();
-             TII->InsertBranch(*MBB, NextBB, nullptr, CurCond, DebugLoc());
-           }
-@@ -1476,11 +1475,13 @@
- 
-     if (!CurFallsThru) {
-       // Check all successors to see if we can move this block before it.
-+      for (MachineBasicBlock *SuccBB : MBB->successors()) {
-+#if 0
-       for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
-            E = MBB->succ_end(); SI != E; ++SI) {
-+#endif
-         // Analyze the branch at the end of the block before the succ.
--        MachineBasicBlock *SuccBB = *SI;
--        MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
-+        MachineFunction::iterator SuccPrev = --SuccBB->getIterator();
- 
-         // If this block doesn't already fall-through to that successor, and if
-         // the succ doesn't already have a block that can fall through into it,
-@@ -1502,8 +1503,8 @@
-       SmallVector<MachineOperand, 4> PrevCond;
-       if (FallThrough != MF.end() &&
-           !TII->AnalyzeBranch(PrevBB, PrevTBB, PrevFBB, PrevCond, true) &&
--          PrevBB.isSuccessor(FallThrough)) {
--        MBB->moveAfter(--MF.end());
-+          PrevBB.isSuccessor(&*FallThrough)) {
-+        MBB->moveAfter(&MF.back());
-         MadeChange = true;
-         return MadeChange;
-       }
-@@ -1522,7 +1523,7 @@
- bool BranchFolder::HoistCommonCode(MachineFunction &MF) {
-   bool MadeChange = false;
-   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ) {
--    MachineBasicBlock *MBB = I++;
-+    MachineBasicBlock *MBB = &*I++;
-     MadeChange |= HoistCommonCodeInSuccs(MBB);
-   }
- 
---- lib/CodeGen/CodeGenPrepare.cpp	2015-01-12 09:22:43.000000000 -0800
-+++ lib/CodeGen/CodeGenPrepare.cpp	2015-12-06 14:55:51.313203408 -0800
-@@ -245,7 +245,8 @@
-   while (MadeChange) {
-     MadeChange = false;
-     for (Function::iterator I = F.begin(); I != F.end(); ) {
--      BasicBlock *BB = I++;
-+      BasicBlock *BB = &*I;
-+      ++I;
-       bool ModifiedDTOnIteration = false;
-       MadeChange |= OptimizeBlock(*BB, ModifiedDTOnIteration);
-       
-@@ -311,7 +312,8 @@
-   bool Changed = false;
-   // Scan all of the blocks in the function, except for the entry block.
-   for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
--    BasicBlock *BB = I++;
-+    BasicBlock *BB = &*I;
-+    ++I;
-     // If the destination block has a single pred, then this is a trivial
-     // edge, just collapse it.
-     BasicBlock *SinglePred = BB->getSinglePredecessor();
-@@ -332,7 +334,7 @@
-         BB->moveBefore(&BB->getParent()->getEntryBlock());
- 
-       // We have erased a block. Update the iterator.
--      I = BB;
-+      I = BB->getIterator();
-     }
-   }
-   return Changed;
-@@ -347,7 +349,8 @@
-   bool MadeChange = false;
-   // Note that this intentionally skips the entry block.
-   for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
--    BasicBlock *BB = I++;
-+    BasicBlock *BB = &*I;
-+    ++I;
- 
-     // If this block doesn't end with an uncond branch, ignore it.
-     BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
-@@ -356,7 +359,7 @@
- 
-     // If the instruction before the branch (skipping debug info) isn't a phi
-     // node, then other stuff is happening here.
--    BasicBlock::iterator BBI = BI;
-+    BasicBlock::iterator BBI(BI);
-     if (BBI != BB->begin()) {
-       --BBI;
-       while (isa<DbgInfoIntrinsic>(BBI)) {
-@@ -553,8 +556,8 @@
-     if (!InsertedCast) {
-       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
-       InsertedCast =
--        CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
--                         InsertPt);
-+        CastInst::Create(CI->getOpcode(), CI->getOperand(0),
-+                         CI->getType(), "", &*InsertPt);
-       MadeChange = true;
-     }
- 
-@@ -648,7 +651,7 @@
-       InsertedCmp =
-         CmpInst::Create(CI->getOpcode(),
-                         CI->getPredicate(),  CI->getOperand(0),
--                        CI->getOperand(1), "", InsertPt);
-+                        CI->getOperand(1), "", &*InsertPt);
-       MadeChange = true;
-     }
- 
-@@ -734,17 +737,17 @@
-       // Sink the shift
-       if (ShiftI->getOpcode() == Instruction::AShr)
-         InsertedShift =
--            BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
-+          BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", &*InsertPt);
-       else
-         InsertedShift =
--            BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
-+          BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", &*InsertPt);
- 
-       // Sink the trunc
-       BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
-       TruncInsertPt++;
- 
-       InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
--                                       TruncI->getType(), "", TruncInsertPt);
-+                                       TruncI->getType(), "", &*TruncInsertPt);
- 
-       MadeChange = true;
- 
-@@ -829,10 +832,10 @@
- 
-       if (ShiftI->getOpcode() == Instruction::AShr)
-         InsertedShift =
--            BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
-+          BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", &*InsertPt);
-       else
-         InsertedShift =
--            BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
-+          BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", &*InsertPt);
- 
-       MadeChange = true;
-     }
-@@ -941,7 +944,7 @@
-     //  %Elt = load i32* %EltAddr
-     //  VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
-     //
--    CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
-+    CondBlock = IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.load");
-     Builder.SetInsertPoint(InsertPt);
-     
-     Value* Gep = Builder.CreateInBoundsGEP(FirstEltPtr, Builder.getInt32(Idx));
-@@ -949,7 +952,8 @@
-     VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
- 
-     // Create "else" block, fill it in the next iteration
--    BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
-+    BasicBlock *NewIfBlock =
-+      CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
-     Builder.SetInsertPoint(InsertPt);
-     Instruction *OldBr = IfBlock->getTerminator();
-     BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
-@@ -1024,7 +1028,8 @@
-     //  %to_store = icmp eq i1 %mask_1, true
-     //  br i1 %to_load, label %cond.store, label %else
-     //
--    Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
-+    Value *Predicate =
-+      Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
-     Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
-                                     ConstantInt::get(Predicate->getType(), 1));
- 
-@@ -1034,15 +1039,17 @@
-     //  %EltAddr = getelementptr i32* %1, i32 0
-     //  %store i32 %OneElt, i32* %EltAddr
-     //
--    BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
-+    BasicBlock *CondBlock =
-+      IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.store");
-     Builder.SetInsertPoint(InsertPt);
--    
-+
-     Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
-     Value* Gep = Builder.CreateInBoundsGEP(FirstEltPtr, Builder.getInt32(Idx));
-     Builder.CreateStore(OneElt, Gep);
- 
-     // Create "else" block, fill it in the next iteration
--    BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
-+    BasicBlock *NewIfBlock =
-+      CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
-     Builder.SetInsertPoint(InsertPt);
-     Instruction *OldBr = IfBlock->getTerminator();
-     BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
-@@ -1085,7 +1092,7 @@
-       // Substituting this can cause recursive simplifications, which can
-       // invalidate our iterator.  Use a WeakVH to hold onto it in case this
-       // happens.
--      WeakVH IterHandle(CurInstIterator);
-+      WeakVH IterHandle(&*CurInstIterator);
- 
-       replaceAndRecursivelySimplify(CI, RetVal,
-                                     TLI ? TLI->getDataLayout() : nullptr,
-@@ -1093,7 +1100,7 @@
- 
-       // If the iterator instruction was recursively deleted, start over at the
-       // start of the block.
--      if (IterHandle != CurInstIterator) {
-+      if (IterHandle != CurInstIterator.getNodePtrUnchecked()) {
-         CurInstIterator = BB->begin();
-         SunkAddrs.clear();
-       }
-@@ -1410,10 +1417,10 @@
-   public:
-     /// \brief Record the position of \p Inst.
-     InsertionHandler(Instruction *Inst) {
--      BasicBlock::iterator It = Inst;
-+      BasicBlock::iterator It = Inst->getIterator();
-       HasPrevInstruction = (It != (Inst->getParent()->begin()));
-       if (HasPrevInstruction)
--        Point.PrevInst = --It;
-+        Point.PrevInst = &*--It;
-       else
-         Point.BB = Inst->getParent();
-     }
-@@ -1425,7 +1432,7 @@
-           Inst->removeFromParent();
-         Inst->insertAfter(Point.PrevInst);
-       } else {
--        Instruction *Position = Point.BB->getFirstInsertionPt();
-+        Instruction *Position = &*Point.BB->getFirstInsertionPt();
-         if (Inst->getParent())
-           Inst->moveBefore(Position);
-         else
-@@ -3191,12 +3198,12 @@
-   if (Repl->use_empty()) {
-     // This can cause recursive deletion, which can invalidate our iterator.
-     // Use a WeakVH to hold onto it in case this happens.
--    WeakVH IterHandle(CurInstIterator);
-+    WeakVH IterHandle(&*CurInstIterator);
-     BasicBlock *BB = CurInstIterator->getParent();
- 
-     RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
- 
--    if (IterHandle != CurInstIterator) {
-+    if (IterHandle != CurInstIterator.getNodePtrUnchecked()) {
-       // If the iterator instruction was recursively deleted, start over at the
-       // start of the block.
-       CurInstIterator = BB->begin();
-@@ -3495,7 +3502,7 @@
- 
-     if (!InsertedTrunc) {
-       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
--      InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
-+      InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
-       InsertedTruncsSet.insert(InsertedTrunc);
-     }
- 
-@@ -3583,7 +3590,8 @@
-   BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
- 
-   // The select itself is replaced with a PHI Node.
--  PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
-+  PHINode *PN = PHINode::Create(SI->getType(), 2, "",
-+                                &NextBlock->front());
-   PN->takeName(SI);
-   PN->addIncoming(SI->getTrueValue(), StartBlock);
-   PN->addIncoming(SI->getFalseValue(), SmallBlock);
-@@ -3646,7 +3654,8 @@
-       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
-       InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0),
-                                               SVI->getOperand(1),
--                                              SVI->getOperand(2), "", InsertPt);
-+                                              SVI->getOperand(2), "",
-+                                              &*InsertPt);
-     }
- 
-     UI->replaceUsesOfWith(SVI, InsertedShuffle);
-@@ -3969,148 +3978,6 @@
-   Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
- }
- 
--// See if we can speculate calls to intrinsic cttz/ctlz.
--//
--// Example:
--// entry:
--//   ...
--//   %cmp = icmp eq i64 %val, 0
--//   br i1 %cmp, label %end.bb, label %then.bb
--//
--// then.bb:
--//   %c = tail call i64 @llvm.cttz.i64(i64 %val, i1 true)
--//   br label %EndBB
--//
--// end.bb:
--//   %cond = phi i64 [ %c, %then.bb ], [ 64, %entry ]
--//
--// ==>
--//
--// entry:
--//   ...
--//   %c = tail call i64 @llvm.cttz.i64(i64 %val, i1 false)
--//
--static bool OptimizeBranchInst(BranchInst *BrInst, const TargetLowering &TLI) {
--  assert(BrInst->isConditional() && "Expected a conditional branch!");
--  BasicBlock *ThenBB = BrInst->getSuccessor(1);
--  BasicBlock *EndBB = BrInst->getSuccessor(0);
--
--  // See if ThenBB contains only one instruction (excluding the
--  // terminator and DbgInfoIntrinsic calls).
--  IntrinsicInst *II = nullptr;
--  CastInst *CI = nullptr;
--  for (BasicBlock::iterator I = ThenBB->begin(),
--                            E = std::prev(ThenBB->end()); I != E; ++I) {
--    // Skip debug info.
--    if (isa<DbgInfoIntrinsic>(I))
--      continue;
--
--    // Check if this is a zero extension or a truncate of a previously
--    // matched call to intrinsic cttz/ctlz.
--    if (II) {
--      // Early exit if we already found a "free" zero extend/truncate.
--      if (CI)
--        return false;
--
--      Type *SrcTy = II->getType();
--      Type *DestTy = I->getType();
--      Value *V;
-- 
--      if (match(cast<Instruction>(I), m_ZExt(m_Value(V))) && V == II) {
--        // Speculate this zero extend only if it is "free" for the target.
--        if (TLI.isZExtFree(SrcTy, DestTy)) {
--          CI = cast<CastInst>(I);
--          continue;
--        }
--      } else if (match(cast<Instruction>(I), m_Trunc(m_Value(V))) && V == II) {
--        // Speculate this truncate only if it is "free" for the target.
--        if (TLI.isTruncateFree(SrcTy, DestTy)) {
--          CI = cast<CastInst>(I);
--          continue;
--        }
--      } else {
--        // Avoid speculating more than one instruction.
--        return false;
--      }
--    }
--
--    // See if this is a call to intrinsic cttz/ctlz.
--    if (match(cast<Instruction>(I), m_Intrinsic<Intrinsic::cttz>())) {
--      // Avoid speculating expensive intrinsic calls.
--      if (!TLI.isCheapToSpeculateCttz())
--        return false;
--    }
--    else if (match(cast<Instruction>(I), m_Intrinsic<Intrinsic::ctlz>())) {
--      // Avoid speculating expensive intrinsic calls.
--      if (!TLI.isCheapToSpeculateCtlz())
--        return false;
--    } else
--      return false;
--    
--    II = cast<IntrinsicInst>(I);
--  }
--
--  // Look for PHI nodes with 'II' as the incoming value from 'ThenBB'.
--  BasicBlock *EntryBB = BrInst->getParent();
--  for (BasicBlock::iterator I = EndBB->begin();
--       PHINode *PN = dyn_cast<PHINode>(I); ++I) {
--    Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
--    Value *OrigV = PN->getIncomingValueForBlock(EntryBB);
--
--    if (!OrigV)
--      return false;
--
--    if (ThenV != II && (!CI || ThenV != CI))
--      return false;
--    
--    if (ConstantInt *CInt = dyn_cast<ConstantInt>(OrigV)) {
--      unsigned BitWidth = II->getType()->getIntegerBitWidth();
--
--      // Don't try to simplify this phi node if 'ThenV' is a cttz/ctlz
--      // intrinsic call, but 'OrigV' is not equal to the 'size-of' in bits
--      // of the value in input to the cttz/ctlz.
--      if (CInt->getValue() != BitWidth)
--        return false;
--
--      // Hoist the call to cttz/ctlz from ThenBB into EntryBB.
--      EntryBB->getInstList().splice(BrInst, ThenBB->getInstList(),
--                                    ThenBB->begin(), std::prev(ThenBB->end()));
-- 
--      // Update PN setting ThenV as the incoming value from both 'EntryBB'
--      // and 'ThenBB'. Eventually, method 'OptimizeInst' will fold this
--      // phi node if all the incoming values are the same.
--      PN->setIncomingValue(PN->getBasicBlockIndex(EntryBB), ThenV);
--      PN->setIncomingValue(PN->getBasicBlockIndex(ThenBB), ThenV);
--
--      // Clear the 'undef on zero' flag of the cttz/ctlz intrinsic call.
--      if (cast<ConstantInt>(II->getArgOperand(1))->isOne()) {
--        Type *Ty = II->getArgOperand(0)->getType();
--        Value *Args[] = { II->getArgOperand(0),
--                          ConstantInt::getFalse(II->getContext()) };
--        Module *M = EntryBB->getParent()->getParent();
--        Value *IF = Intrinsic::getDeclaration(M, II->getIntrinsicID(), Ty);
--        IRBuilder<> Builder(II);
--        Instruction *NewI = Builder.CreateCall(IF, Args);
--
--        // Replace the old call to cttz/ctlz.
--        II->replaceAllUsesWith(NewI);
--        II->eraseFromParent();
--      }
-- 
--      // Update BrInst condition so that the branch to EndBB is always taken.
--      // Later on, method 'ConstantFoldTerminator' will simplify this branch
--      // replacing it with a direct branch to 'EndBB'.
--      // As a side effect, CodeGenPrepare will attempt to simplify the control
--      // flow graph by deleting basic block 'ThenBB' and merging 'EntryBB' into
--      // 'EndBB' (calling method 'EliminateFallThrough').
--      BrInst->setCondition(ConstantInt::getTrue(BrInst->getContext()));
--      return true;
--    }
--  }
--
--  return false;
--}
--
- /// Some targets can do store(extractelement) with one instruction.
- /// Try to push the extractelement towards the stores when the target
- /// has this feature and this is profitable.
-@@ -4263,34 +4130,6 @@
-   if (isa<ExtractElementInst>(I))
-     return OptimizeExtractElementInst(I);
- 
--  if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
--    if (TLI && BI->isConditional() && BI->getCondition()->hasOneUse()) {
--      // Check if the branch condition compares a value agaist zero.
--      if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
--        if (ICI->getPredicate() == ICmpInst::ICMP_EQ &&
--            match(ICI->getOperand(1), m_Zero())) {
--          BasicBlock *ThenBB = BI->getSuccessor(1);
--          BasicBlock *EndBB = BI->getSuccessor(0);
--
--          // Check if ThenBB is only reachable from this basic block; also,
--          // check if EndBB has more than one predecessor.
--          if (ThenBB->getSinglePredecessor() &&
--              !EndBB->getSinglePredecessor()) {
--            TerminatorInst *TI = ThenBB->getTerminator();
--
--            if (TI->getNumSuccessors() == 1 && TI->getSuccessor(0) == EndBB &&
--                // Try to speculate calls to intrinsic cttz/ctlz from 'ThenBB'.
--                OptimizeBranchInst(BI, *TLI)) {
--              ModifiedDT = true;
--              return true;
--            }
--          }
--        }
--      }
--    }
--    return false;
--  }
--
-   return false;
- }
- 
-@@ -4303,7 +4142,7 @@
- 
-   CurInstIterator = BB.begin();
-   while (CurInstIterator != BB.end()) {
--    MadeChange |= OptimizeInst(CurInstIterator++, ModifiedDT);
-+    MadeChange |= OptimizeInst(&*CurInstIterator++, ModifiedDT);
-     if (ModifiedDT)
-       return true;
-   }
-@@ -4320,7 +4159,7 @@
-   for (BasicBlock &BB : F) {
-     Instruction *PrevNonDbgInst = nullptr;
-     for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
--      Instruction *Insn = BI++;
-+      Instruction *Insn = &*BI++;
-       DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
-       // Leave dbg.values that refer to an alloca alone. These
-       // instrinsics describe the address of a variable (= the alloca)
-@@ -4337,7 +4176,7 @@
-         DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
-         DVI->removeFromParent();
-         if (isa<PHINode>(VI))
--          DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
-+          DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
-         else
-           DVI->insertAfter(VI);
-         MadeChange = true;
-@@ -4361,7 +4200,7 @@
-     return false;
-   bool MadeChange = false;
-   for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
--    BasicBlock *BB = I++;
-+    BasicBlock *BB = &*I++;
- 
-     // Does this BB end with the following?
-     //   %andVal = and %val, #single-bit-set
---- lib/CodeGen/DFAPacketizer.cpp	2014-10-13 18:03:16.000000000 -0700
-+++ lib/CodeGen/DFAPacketizer.cpp	2015-12-06 18:00:08.967241318 -0800
-@@ -147,7 +147,7 @@
-                                          MachineInstr *MI) {
-   if (CurrentPacketMIs.size() > 1) {
-     MachineInstr *MIFirst = CurrentPacketMIs.front();
--    finalizeBundle(*MBB, MIFirst, MI);
-+    finalizeBundle(*MBB, MIFirst->getIterator(), MI->getIterator());
-   }
-   CurrentPacketMIs.clear();
-   ResourceTracker->clearResources();
---- lib/CodeGen/ExecutionDepsFix.cpp	2014-12-17 11:13:47.000000000 -0800
-+++ lib/CodeGen/ExecutionDepsFix.cpp	2015-12-06 14:03:54.050682968 -0800
-@@ -753,7 +753,7 @@
-         AliasMap[*AI].push_back(i);
-   }
- 
--  MachineBasicBlock *Entry = MF->begin();
-+  MachineBasicBlock *Entry = &*MF->begin();
-   ReversePostOrderTraversal<MachineBasicBlock*> RPOT(Entry);
-   SmallVector<MachineBasicBlock*, 16> Loops;
-   for (ReversePostOrderTraversal<MachineBasicBlock*>::rpo_iterator
---- lib/CodeGen/ExpandISelPseudos.cpp	2014-10-14 00:22:08.000000000 -0700
-+++ lib/CodeGen/ExpandISelPseudos.cpp	2015-12-06 14:17:23.351013837 -0800
-@@ -50,7 +50,7 @@
- 
-   // Iterate through each instruction in the function, looking for pseudos.
-   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
--    MachineBasicBlock *MBB = I;
-+    MachineBasicBlock *MBB = &*I;
-     for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
-          MBBI != MBBE; ) {
-       MachineInstr *MI = MBBI++;
-@@ -63,7 +63,7 @@
-         // The expansion may involve new basic blocks.
-         if (NewMBB != MBB) {
-           MBB = NewMBB;
--          I = NewMBB;
-+          I = NewMBB->getIterator();
-           MBBI = NewMBB->begin();
-           MBBE = NewMBB->end();
-         }
---- lib/CodeGen/ForwardControlFlowIntegrity.cpp	2015-01-14 03:23:27.000000000 -0800
-+++ lib/CodeGen/ForwardControlFlowIntegrity.cpp	2015-12-06 18:01:31.650156258 -0800
-@@ -329,7 +329,7 @@
-       Check = TempBuilder.CreateICmpEQ(NewFunPtr, FunPtr);
-     BasicBlock *InvalidPtrBlock =
-         BasicBlock::Create(M.getContext(), "invalid.ptr", CurF, 0);
--    BasicBlock *ContinuationBB = CurBB->splitBasicBlock(I);
-+    BasicBlock *ContinuationBB = CurBB->splitBasicBlock(I->getIterator());
- 
-     // Remove the unconditional branch that connects the two blocks.
-     TerminatorInst *TermInst = CurBB->getTerminator();
---- lib/CodeGen/GCStrategy.cpp	2015-01-07 11:07:50.000000000 -0800
-+++ lib/CodeGen/GCStrategy.cpp	2015-12-06 18:08:32.675654207 -0800
-@@ -156,12 +156,13 @@
-                                                           unsigned Count) {
-   // Scroll past alloca instructions.
-   BasicBlock::iterator IP = F.getEntryBlock().begin();
--  while (isa<AllocaInst>(IP)) ++IP;
-+  while (isa<AllocaInst>(IP))
-+    ++IP;
- 
-   // Search for initializers in the initial BB.
-   SmallPtrSet<AllocaInst*,16> InitedRoots;
--  for (; !CouldBecomeSafePoint(IP); ++IP)
--    if (StoreInst *SI = dyn_cast<StoreInst>(IP))
-+  for (; !CouldBecomeSafePoint(&*IP); ++IP)
-+    if (StoreInst *SI = dyn_cast<StoreInst>(&*IP))
-       if (AllocaInst *AI =
-           dyn_cast<AllocaInst>(SI->getOperand(1)->stripPointerCasts()))
-         InitedRoots.insert(AI);
---- lib/CodeGen/GlobalMerge.cpp	2015-01-14 03:23:27.000000000 -0800
-+++ lib/CodeGen/GlobalMerge.cpp	2015-12-06 18:44:54.895620825 -0800
-@@ -289,61 +289,61 @@
-   setMustKeepGlobalVariables(M);
- 
-   // Grab all non-const globals.
--  for (Module::global_iterator I = M.global_begin(),
--         E = M.global_end(); I != E; ++I) {
-+  for (auto &I : M.globals()) {
-     // Merge is safe for "normal" internal or external globals only
--    if (I->isDeclaration() || I->isThreadLocal() || I->hasSection())
-+    if (I.isDeclaration() || I.isThreadLocal() || I.hasSection())
-       continue;
- 
--    if (!(EnableGlobalMergeOnExternal && I->hasExternalLinkage()) &&
--        !I->hasInternalLinkage())
-+    if (!(EnableGlobalMergeOnExternal && I.hasExternalLinkage()) &&
-+        !I.hasInternalLinkage())
-       continue;
- 
--    PointerType *PT = dyn_cast<PointerType>(I->getType());
-+    PointerType *PT = dyn_cast<PointerType>(I.getType());
-     assert(PT && "Global variable is not a pointer!");
- 
-     unsigned AddressSpace = PT->getAddressSpace();
- 
-     // Ignore fancy-aligned globals for now.
--    unsigned Alignment = DL->getPreferredAlignment(I);
--    Type *Ty = I->getType()->getElementType();
-+    unsigned Alignment = DL->getPreferredAlignment(&I);
-+    Type *Ty = I.getType()->getElementType();
-     if (Alignment > DL->getABITypeAlignment(Ty))
-       continue;
- 
-     // Ignore all 'special' globals.
--    if (I->getName().startswith("llvm.") ||
--        I->getName().startswith(".llvm."))
-+    if (I.getName().startswith("llvm.") ||
-+        I.getName().startswith(".llvm."))
-       continue;
- 
-     // Ignore all "required" globals:
--    if (isMustKeepGlobalVariable(I))
-+    if (isMustKeepGlobalVariable(&I))
-       continue;
- 
-     if (DL->getTypeAllocSize(Ty) < MaxOffset) {
--      if (TargetLoweringObjectFile::getKindForGlobal(I, *TM).isBSSLocal())
--        BSSGlobals[AddressSpace].push_back(I);
--      else if (I->isConstant())
--        ConstGlobals[AddressSpace].push_back(I);
-+      if (TargetLoweringObjectFile::getKindForGlobal(&I, *TM).isBSSLocal())
-+        BSSGlobals[AddressSpace].push_back(&I);
-+      else if (I.isConstant())
-+        ConstGlobals[AddressSpace].push_back(&I);
-       else
--        Globals[AddressSpace].push_back(I);
-+        Globals[AddressSpace].push_back(&I);
-     }
-   }
- 
--  for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator
--       I = Globals.begin(), E = Globals.end(); I != E; ++I)
--    if (I->second.size() > 1)
--      Changed |= doMerge(I->second, M, false, I->first);
--
--  for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator
--       I = BSSGlobals.begin(), E = BSSGlobals.end(); I != E; ++I)
--    if (I->second.size() > 1)
--      Changed |= doMerge(I->second, M, false, I->first);
--
--  if (EnableGlobalMergeOnConst)
--    for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator
--         I = ConstGlobals.begin(), E = ConstGlobals.end(); I != E; ++I)
--      if (I->second.size() > 1)
--        Changed |= doMerge(I->second, M, true, I->first);
-+  for (auto &G : Globals) {
-+    if (G.second.size() > 1)
-+      Changed |= doMerge(G.second, M, false, G.first);
-+  }
-+
-+  for (auto &G : BSSGlobals) {
-+    if (G.second.size() > 1)
-+      Changed |= doMerge(G.second, M, false, G.first);
-+  }
-+
-+  if (EnableGlobalMergeOnConst) {
-+    for (auto &G : ConstGlobals) {
-+      if (G.second.size() > 1)
-+        Changed |= doMerge(G.second, M, true, G.first);
-+    }
-+  }
- 
-   return Changed;
- }
---- lib/CodeGen/IfConversion.cpp	2014-10-14 00:22:08.000000000 -0700
-+++ lib/CodeGen/IfConversion.cpp	2015-12-06 19:35:07.755981678 -0800
-@@ -460,11 +460,15 @@
- /// getNextBlock - Returns the next block in the function blocks ordering. If
- /// it is the end, returns NULL.
- static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
--  MachineFunction::iterator I = BB;
-+  MachineFunction::iterator I = BB->getIterator();
-   MachineFunction::iterator E = BB->getParent()->end();
-+  if (I == E)
-+    return nullptr;
-+
-   if (++I == E)
-     return nullptr;
--  return I;
-+
-+  return &*I;
- }
- 
- /// ValidSimple - Returns true if the 'true' block (along with its
-@@ -528,12 +532,13 @@
- 
-   MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
-   if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
--    MachineFunction::iterator I = TrueBBI.BB;
-+    MachineFunction::iterator I = TrueBBI.BB->getIterator();
-     if (++I == TrueBBI.BB->getParent()->end())
-       return false;
--    TExit = I;
-+
-+    TExit = &*I;
-   }
--  return TExit && TExit == FalseBBI.BB;
-+  return TExit && (TExit == FalseBBI.BB);
- }
- 
- /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
-@@ -910,10 +915,8 @@
- /// candidates.
- void IfConverter::AnalyzeBlocks(MachineFunction &MF,
-                                 std::vector<IfcvtToken*> &Tokens) {
--  for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
--    MachineBasicBlock *BB = I;
--    AnalyzeBlock(BB, Tokens);
--  }
-+  for (auto &BB : MF)
-+    AnalyzeBlock(&BB, Tokens);
- 
-   // Sort to favor more complex ifcvt scheme.
-   std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
-@@ -923,14 +926,14 @@
- /// that all the intervening blocks are empty (given BB can fall through to its
- /// next block).
- static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
--  MachineFunction::iterator PI = BB;
-+  MachineFunction::iterator PI = BB->getIterator();
-   MachineFunction::iterator I = std::next(PI);
--  MachineFunction::iterator TI = ToBB;
-+  MachineFunction::iterator TI = ToBB->getIterator();
-   MachineFunction::iterator E = BB->getParent()->end();
-   while (I != TI) {
-     // Check isSuccessor to avoid case where the next block is empty, but
-     // it's not a successor.
--    if (I == E || !I->empty() || !PI->isSuccessor(I))
-+    if (I == E || !I->empty() || !PI->isSuccessor(&*I))
-       return false;
-     PI = I++;
-   }
---- lib/CodeGen/InterferenceCache.cpp	2014-04-21 19:02:50.000000000 -0700
-+++ lib/CodeGen/InterferenceCache.cpp	2015-12-06 19:36:56.386076813 -0800
-@@ -143,7 +143,8 @@
-     PrevPos = Start;
-   }
- 
--  MachineFunction::const_iterator MFI = MF->getBlockNumbered(MBBNum);
-+  MachineFunction::const_iterator MFI =
-+    MF->getBlockNumbered(MBBNum)->getIterator();
-   BlockInterference *BI = &Blocks[MBBNum];
-   ArrayRef<SlotIndex> RegMaskSlots;
-   ArrayRef<const uint32_t*> RegMaskBits;
---- lib/CodeGen/IntrinsicLowering.cpp	2014-08-30 11:33:35.000000000 -0700
-+++ lib/CodeGen/IntrinsicLowering.cpp	2015-12-06 19:45:17.855570385 -0800
-@@ -75,7 +75,7 @@
-   Constant* FCache = M->getOrInsertFunction(NewFn,
-                                   FunctionType::get(RetTy, ParamTys, false));
- 
--  IRBuilder<> Builder(CI->getParent(), CI);
-+  IRBuilder<> Builder(CI->getParent(), CI->getIterator());
-   SmallVector<Value *, 8> Args(ArgBegin, ArgEnd);
-   CallInst *NewCI = Builder.CreateCall(FCache, Args);
-   NewCI->setName(CI->getName());
-@@ -94,71 +94,73 @@
- 
- void IntrinsicLowering::AddPrototypes(Module &M) {
-   LLVMContext &Context = M.getContext();
--  for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
--    if (I->isDeclaration() && !I->use_empty())
--      switch (I->getIntrinsicID()) {
-+  for (auto &I : M) {
-+    if (I.isDeclaration() && !I.use_empty()) {
-+      switch (I.getIntrinsicID()) {
-       default: break;
-       case Intrinsic::setjmp:
--        EnsureFunctionExists(M, "setjmp", I->arg_begin(), I->arg_end(),
--                             Type::getInt32Ty(M.getContext()));
--        break;
-+               EnsureFunctionExists(M, "setjmp", I.arg_begin(), I.arg_end(),
-+                                    Type::getInt32Ty(M.getContext()));
-+               break;
-       case Intrinsic::longjmp:
--        EnsureFunctionExists(M, "longjmp", I->arg_begin(), I->arg_end(),
--                             Type::getVoidTy(M.getContext()));
--        break;
-+               EnsureFunctionExists(M, "longjmp", I.arg_begin(), I.arg_end(),
-+                                    Type::getVoidTy(M.getContext()));
-+               break;
-       case Intrinsic::siglongjmp:
--        EnsureFunctionExists(M, "abort", I->arg_end(), I->arg_end(),
--                             Type::getVoidTy(M.getContext()));
--        break;
-+               EnsureFunctionExists(M, "abort", I.arg_end(), I.arg_end(),
-+                                    Type::getVoidTy(M.getContext()));
-+               break;
-       case Intrinsic::memcpy:
--        M.getOrInsertFunction("memcpy",
--          Type::getInt8PtrTy(Context),
--                              Type::getInt8PtrTy(Context), 
--                              Type::getInt8PtrTy(Context), 
--                              DL.getIntPtrType(Context), nullptr);
--        break;
-+               M.getOrInsertFunction("memcpy",
-+                                     Type::getInt8PtrTy(Context),
-+                                     Type::getInt8PtrTy(Context),
-+                                     Type::getInt8PtrTy(Context),
-+                                     DL.getIntPtrType(Context), nullptr);
-+               break;
-       case Intrinsic::memmove:
--        M.getOrInsertFunction("memmove",
--          Type::getInt8PtrTy(Context),
--                              Type::getInt8PtrTy(Context), 
--                              Type::getInt8PtrTy(Context), 
--                              DL.getIntPtrType(Context), nullptr);
--        break;
-+               M.getOrInsertFunction("memmove",
-+                                     Type::getInt8PtrTy(Context),
-+                                     Type::getInt8PtrTy(Context),
-+                                     Type::getInt8PtrTy(Context),
-+                                     DL.getIntPtrType(Context), nullptr);
-+               break;
-       case Intrinsic::memset:
--        M.getOrInsertFunction("memset",
--          Type::getInt8PtrTy(Context),
--                              Type::getInt8PtrTy(Context), 
--                              Type::getInt32Ty(M.getContext()), 
--                              DL.getIntPtrType(Context), nullptr);
--        break;
-+               M.getOrInsertFunction("memset",
-+                                     Type::getInt8PtrTy(Context),
-+                                     Type::getInt8PtrTy(Context),
-+                                     Type::getInt32Ty(M.getContext()),
-+                                     DL.getIntPtrType(Context), nullptr);
-+               break;
-       case Intrinsic::sqrt:
--        EnsureFPIntrinsicsExist(M, I, "sqrtf", "sqrt", "sqrtl");
--        break;
-+               EnsureFPIntrinsicsExist(M, &I, "sqrtf", "sqrt", "sqrtl");
-+               break;
-       case Intrinsic::sin:
--        EnsureFPIntrinsicsExist(M, I, "sinf", "sin", "sinl");
--        break;
-+               EnsureFPIntrinsicsExist(M, &I, "sinf", "sin", "sinl");
-+               break;
-       case Intrinsic::cos:
--        EnsureFPIntrinsicsExist(M, I, "cosf", "cos", "cosl");
--        break;
-+               EnsureFPIntrinsicsExist(M, &I, "cosf", "cos", "cosl");
-+               break;
-       case Intrinsic::pow:
--        EnsureFPIntrinsicsExist(M, I, "powf", "pow", "powl");
--        break;
-+               EnsureFPIntrinsicsExist(M, &I, "powf", "pow", "powl");
-+               break;
-       case Intrinsic::log:
--        EnsureFPIntrinsicsExist(M, I, "logf", "log", "logl");
--        break;
-+               EnsureFPIntrinsicsExist(M, &I, "logf", "log", "logl");
-+               break;
-       case Intrinsic::log2:
--        EnsureFPIntrinsicsExist(M, I, "log2f", "log2", "log2l");
--        break;
-+               EnsureFPIntrinsicsExist(M, &I, "log2f", "log2", "log2l");
-+               break;
-       case Intrinsic::log10:
--        EnsureFPIntrinsicsExist(M, I, "log10f", "log10", "log10l");
--        break;
-+               EnsureFPIntrinsicsExist(M, &I, "log10f", "log10", "log10l");
-+               break;
-       case Intrinsic::exp:
--        EnsureFPIntrinsicsExist(M, I, "expf", "exp", "expl");
--        break;
-+               EnsureFPIntrinsicsExist(M, &I, "expf", "exp", "expl");
-+               break;
-       case Intrinsic::exp2:
--        EnsureFPIntrinsicsExist(M, I, "exp2f", "exp2", "exp2l");
--        break;
-+               EnsureFPIntrinsicsExist(M, &I, "exp2f", "exp2", "exp2l");
-+               break;
-       }
-+    }
-+  }
- }
- 
- /// LowerBSWAP - Emit the code to lower bswap of V before the specified
-@@ -168,7 +170,7 @@
- 
-   unsigned BitSize = V->getType()->getPrimitiveSizeInBits();
-   
--  IRBuilder<> Builder(IP->getParent(), IP);
-+  IRBuilder<> Builder(IP->getParent(), IP->getIterator());
- 
-   switch(BitSize) {
-   default: llvm_unreachable("Unhandled type size of value to byteswap!");
-@@ -268,7 +270,7 @@
-     0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL
-   };
- 
--  IRBuilder<> Builder(IP->getParent(), IP);
-+  IRBuilder<> Builder(IP->getParent(), IP->getIterator());
- 
-   unsigned BitSize = V->getType()->getPrimitiveSizeInBits();
-   unsigned WordSize = (BitSize + 63) / 64;
-@@ -301,7 +303,7 @@
- /// instruction IP.
- static Value *LowerCTLZ(LLVMContext &Context, Value *V, Instruction *IP) {
- 
--  IRBuilder<> Builder(IP->getParent(), IP);
-+  IRBuilder<> Builder(IP->getParent(), IP->getIterator());
- 
-   unsigned BitSize = V->getType()->getPrimitiveSizeInBits();
-   for (unsigned i = 1; i < BitSize; i <<= 1) {
-@@ -338,7 +340,7 @@
- }
- 
- void IntrinsicLowering::LowerIntrinsicCall(CallInst *CI) {
--  IRBuilder<> Builder(CI->getParent(), CI);
-+  IRBuilder<> Builder(CI->getParent(), CI->getIterator());
-   LLVMContext &Context = CI->getContext();
- 
-   const Function *Callee = CI->getCalledFunction();
---- lib/CodeGen/LiveDebugVariables.cpp	2015-01-14 03:23:27.000000000 -0800
-+++ lib/CodeGen/LiveDebugVariables.cpp	2015-12-06 19:51:37.891248865 -0800
-@@ -480,7 +480,7 @@
-   bool Changed = false;
-   for (MachineFunction::iterator MFI = mf.begin(), MFE = mf.end(); MFI != MFE;
-        ++MFI) {
--    MachineBasicBlock *MBB = MFI;
-+    MachineBasicBlock *MBB = &*MFI;
-     for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
-          MBBI != MBBE;) {
-       if (!MBBI->isDebugValue()) {
-@@ -974,11 +974,11 @@
-     SlotIndex Stop = I.stop();
-     unsigned LocNo = I.value();
-     DEBUG(dbgs() << "\t[" << Start << ';' << Stop << "):" << LocNo);
--    MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start);
--    SlotIndex MBBEnd = LIS.getMBBEndIdx(MBB);
-+    MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator();
-+    SlotIndex MBBEnd = LIS.getMBBEndIdx(&*MBB);
- 
-     DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
--    insertDebugValue(MBB, Start, LocNo, LIS, TII);
-+    insertDebugValue(&*MBB, Start, LocNo, LIS, TII);
-     // This interval may span multiple basic blocks.
-     // Insert a DBG_VALUE into each one.
-     while(Stop > MBBEnd) {
-@@ -986,9 +986,9 @@
-       Start = MBBEnd;
-       if (++MBB == MFEnd)
-         break;
--      MBBEnd = LIS.getMBBEndIdx(MBB);
-+      MBBEnd = LIS.getMBBEndIdx(&*MBB);
-       DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
--      insertDebugValue(MBB, Start, LocNo, LIS, TII);
-+      insertDebugValue(&*MBB, Start, LocNo, LIS, TII);
-     }
-     DEBUG(dbgs() << '\n');
-     if (MBB == MFEnd)
---- lib/CodeGen/LiveIntervalAnalysis.cpp	2014-12-23 18:11:43.000000000 -0800
-+++ lib/CodeGen/LiveIntervalAnalysis.cpp	2015-12-06 19:52:56.875852273 -0800
-@@ -211,7 +211,7 @@
-   // Find all instructions with regmask operands.
-   for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
-        MBBI != E; ++MBBI) {
--    MachineBasicBlock *MBB = MBBI;
-+    MachineBasicBlock *MBB = &*MBBI;
-     std::pair<unsigned, unsigned> &RMB = RegMaskBlocks[MBB->getNumber()];
-     RMB.first = RegMaskSlots.size();
-     for (MachineBasicBlock::iterator MI = MBB->begin(), ME = MBB->end();
-@@ -285,7 +285,7 @@
-   // Check all basic blocks for live-ins.
-   for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
-        MFI != MFE; ++MFI) {
--    const MachineBasicBlock *MBB = MFI;
-+    const MachineBasicBlock *MBB = &*MFI;
- 
-     // We only care about ABI blocks: Entry + landing pads.
-     if ((MFI != MF->begin() && !MBB->isLandingPad()) || MBB->livein_empty())
---- lib/CodeGen/LiveVariables.cpp	2014-10-14 00:22:08.000000000 -0700
-+++ lib/CodeGen/LiveVariables.cpp	2015-12-06 19:54:20.348152143 -0800
-@@ -639,7 +639,7 @@
-   // function.  This guarantees that we will see the definition of a virtual
-   // register before its uses due to dominance properties of SSA (except for PHI
-   // nodes, which are treated as a special case).
--  MachineBasicBlock *Entry = MF->begin();
-+  MachineBasicBlock *Entry = &MF->front();
-   SmallPtrSet<MachineBasicBlock*,16> Visited;
- 
-   for (MachineBasicBlock *MBB : depth_first_ext(Entry, Visited)) {
---- lib/CodeGen/LocalStackSlotAllocation.cpp	2014-12-01 14:52:56.000000000 -0800
-+++ lib/CodeGen/LocalStackSlotAllocation.cpp	2015-12-06 19:56:09.955965495 -0800
-@@ -324,7 +324,7 @@
-   // Sort the frame references by local offset
-   array_pod_sort(FrameReferenceInsns.begin(), FrameReferenceInsns.end());
- 
--  MachineBasicBlock *Entry = Fn.begin();
-+  MachineBasicBlock *Entry = &Fn.front();
- 
-   unsigned BaseReg = 0;
-   int64_t BaseOffset = 0;
---- lib/CodeGen/MachineBasicBlock.cpp	2014-12-22 05:00:36.000000000 -0800
-+++ lib/CodeGen/MachineBasicBlock.cpp	2015-12-06 20:28:52.972371805 -0800
-@@ -300,8 +300,8 @@
- 
-   for (const_instr_iterator I = instr_begin(); I != instr_end(); ++I) {
-     if (Indexes) {
--      if (Indexes->hasIndex(I))
--        OS << Indexes->getInstructionIndex(I);
-+      if (Indexes->hasIndex(&*I))
-+        OS << Indexes->getInstructionIndex(&*I);
-       OS << '\t';
-     }
-     OS << '\t';
-@@ -372,12 +372,11 @@
- }
- 
- void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
--  getParent()->splice(NewAfter, this);
-+  getParent()->splice(NewAfter->getIterator(), getIterator());
- }
- 
- void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
--  MachineFunction::iterator BBI = NewBefore;
--  getParent()->splice(++BBI, this);
-+  getParent()->splice(++NewBefore->getIterator(), getIterator());
- }
- 
- void MachineBasicBlock::updateTerminator() {
-@@ -623,14 +622,14 @@
- }
- 
- bool MachineBasicBlock::canFallThrough() {
--  MachineFunction::iterator Fallthrough = this;
-+  MachineFunction::iterator Fallthrough = getIterator();
-   ++Fallthrough;
-   // If FallthroughBlock is off the end of the function, it can't fall through.
-   if (Fallthrough == getParent()->end())
-     return false;
- 
-   // If FallthroughBlock isn't a successor, no fallthrough is possible.
--  if (!isSuccessor(Fallthrough))
-+  if (!isSuccessor(&*Fallthrough))
-     return false;
- 
-   // Analyze the branches, if any, at the end of the block.
-@@ -721,7 +720,7 @@
-   if (LV)
-     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
-          I != E; ++I) {
--      MachineInstr *MI = I;
-+      MachineInstr *MI = &*I;
-       for (MachineInstr::mop_iterator OI = MI->operands_begin(),
-            OE = MI->operands_end(); OI != OE; ++OI) {
-         if (!OI->isReg() || OI->getReg() == 0 ||
-@@ -741,7 +740,7 @@
-   if (LIS) {
-     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
-          I != E; ++I) {
--      MachineInstr *MI = I;
-+      MachineInstr *MI = &*I;
- 
-       for (MachineInstr::mop_iterator OI = MI->operands_begin(),
-            OE = MI->operands_end(); OI != OE; ++OI) {
-@@ -763,7 +762,7 @@
-   if (Indexes) {
-     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
-          I != E; ++I)
--      Terminators.push_back(I);
-+      Terminators.push_back(&*I);
-   }
- 
-   updateTerminator();
-@@ -772,7 +771,7 @@
-     SmallVector<MachineInstr*, 4> NewTerminators;
-     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
-          I != E; ++I)
--      NewTerminators.push_back(I);
-+      NewTerminators.push_back(&*I);
- 
-     for (SmallVectorImpl<MachineInstr*>::iterator I = Terminators.begin(),
-         E = Terminators.end(); I != E; ++I) {
-@@ -794,9 +793,9 @@
-            I != E; ++I) {
-         // Some instructions may have been moved to NMBB by updateTerminator(),
-         // so we first remove any instruction that already has an index.
--        if (Indexes->hasIndex(I))
--          Indexes->removeMachineInstrFromMaps(I);
--        Indexes->insertMachineInstrInMaps(I);
-+        if (Indexes->hasIndex(&*I))
-+          Indexes->removeMachineInstrFromMaps(&*I);
-+        Indexes->insertMachineInstrInMaps(&*I);
-       }
-     }
-   }
-@@ -811,7 +810,7 @@
- 
-   // Inherit live-ins from the successor
-   for (MachineBasicBlock::livein_iterator I = Succ->livein_begin(),
--         E = Succ->livein_end(); I != E; ++I)
-+       E = Succ->livein_end(); I != E; ++I)
-     NMBB->addLiveIn(*I);
- 
-   // Update LiveVariables.
-@@ -824,7 +823,7 @@
-         if (!(--I)->addRegisterKilled(Reg, TRI, /* addIfNotFound= */ false))
-           continue;
-         if (TargetRegisterInfo::isVirtualRegister(Reg))
--          LV->getVarInfo(Reg).Kills.push_back(I);
-+          LV->getVarInfo(Reg).Kills.push_back(&*I);
-         DEBUG(dbgs() << "Restored terminator kill: " << *I);
-         break;
-       }
-@@ -943,7 +942,7 @@
- 
- MachineBasicBlock::instr_iterator
- MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) {
--  unbundleSingleMI(I);
-+  unbundleSingleMI(&*I);
-   return Insts.erase(I);
- }
- 
-@@ -1038,12 +1037,12 @@
- 
-   if (!DestA && !DestB) {
-     // Block falls through to successor.
--    DestA = FallThru;
--    DestB = FallThru;
-+    DestA = &*FallThru;
-+    DestB = &*FallThru;
-   } else if (DestA && !DestB) {
-     if (isCond)
-       // Block ends in conditional jump that falls through to successor.
--      DestB = FallThru;
-+      DestB = &*FallThru;
-   } else {
-     assert(DestA && DestB && isCond &&
-            "CFG in a bad state. Cannot correct CFG edges");
---- lib/CodeGen/MachineBlockFrequencyInfo.cpp	2014-06-26 15:52:05.000000000 -0700
-+++ lib/CodeGen/MachineBlockFrequencyInfo.cpp	2015-12-06 20:30:07.075098190 -0800
-@@ -57,7 +57,7 @@
- 
-   static inline
-   const NodeType *getEntryNode(const MachineBlockFrequencyInfo *G) {
--    return G->getFunction()->begin();
-+    return &G->getFunction()->front();
-   }
- 
-   static ChildIteratorType child_begin(const NodeType *N) {
---- lib/CodeGen/MachineBlockPlacement.cpp	2015-01-03 09:58:24.000000000 -0800
-+++ lib/CodeGen/MachineBlockPlacement.cpp	2015-12-06 20:45:33.550025788 -0800
-@@ -471,14 +471,14 @@
-     const BlockFilterSet *BlockFilter) {
-   for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F.end(); I != E;
-        ++I) {
--    if (BlockFilter && !BlockFilter->count(I))
-+    if (BlockFilter && !BlockFilter->count(&*I))
-       continue;
--    if (BlockToChain[I] != &PlacedChain) {
-+    if (BlockToChain[&*I] != &PlacedChain) {
-       PrevUnplacedBlockIt = I;
-       // Now select the head of the chain to which the unplaced block belongs
-       // as the block to place. This will force the entire chain to be placed,
-       // and satisfies the requirements of merging chains.
--      return *BlockToChain[I]->begin();
-+      return *BlockToChain[&*I]->begin();
-     }
-   }
-   return nullptr;
-@@ -878,9 +878,9 @@
-   // the assumptions of the remaining algorithm.
-   SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
-   for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
--    MachineBasicBlock *BB = FI;
--    BlockChain *Chain
--      = new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
-+    MachineBasicBlock *BB = &*FI;
-+    BlockChain *Chain =
-+      new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
-     // Also, merge any blocks which we cannot reason about and must preserve
-     // the exact fallthrough behavior for.
-     for (;;) {
-@@ -890,7 +890,7 @@
-         break;
- 
-       MachineFunction::iterator NextFI(std::next(FI));
--      MachineBasicBlock *NextBB = NextFI;
-+      MachineBasicBlock *NextBB = &*NextFI;
-       // Ensure that the layout successor is a viable block, as we know that
-       // fallthrough is a possibility.
-       assert(NextFI != FE && "Can't fallthrough past the last block.");
-@@ -944,8 +944,9 @@
-     // Crash at the end so we get all of the debugging output first.
-     bool BadFunc = false;
-     FunctionBlockSetType FunctionBlockSet;
--    for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
--      FunctionBlockSet.insert(FI);
-+
-+    for (MachineBasicBlock &MBB : F)
-+      FunctionBlockSet.insert(&MBB);
- 
-     for (BlockChain::iterator BCI = FunctionChain.begin(),
-                               BCE = FunctionChain.end();
-@@ -969,21 +970,19 @@
- 
-   // Splice the blocks into place.
-   MachineFunction::iterator InsertPos = F.begin();
--  for (BlockChain::iterator BI = FunctionChain.begin(),
--                            BE = FunctionChain.end();
--       BI != BE; ++BI) {
--    DEBUG(dbgs() << (BI == FunctionChain.begin() ? "Placing chain "
-+  for (MachineBasicBlock *BI : FunctionChain) {
-+    DEBUG(dbgs() << (BI == *FunctionChain.begin() ? "Placing chain "
-                                                   : "          ... ")
--          << getBlockName(*BI) << "\n");
--    if (InsertPos != MachineFunction::iterator(*BI))
--      F.splice(InsertPos, *BI);
-+          << getBlockName(BI) << "\n");
-+    if (InsertPos != MachineFunction::iterator(BI))
-+      F.splice(InsertPos, BI->getIterator());
-     else
-       ++InsertPos;
- 
-     // Update the terminator of the previous block.
--    if (BI == FunctionChain.begin())
-+    if (BI == *FunctionChain.begin())
-       continue;
--    MachineBasicBlock *PrevBB = std::prev(MachineFunction::iterator(*BI));
-+    MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(BI));
- 
-     // FIXME: It would be awesome of updateTerminator would just return rather
-     // than assert when the branch cannot be analyzed in order to remove this
-@@ -1002,7 +1001,7 @@
-       // is mistakenly pointing to "*BI".
-       //
-       bool needUpdateBr = true;
--      if (!Cond.empty() && (!FBB || FBB == *BI)) {
-+      if (!Cond.empty() && (!FBB || FBB == BI)) {
-         PrevBB->updateTerminator();
-         needUpdateBr = false;
-         Cond.clear();
-@@ -1050,7 +1049,7 @@
-     return;  // Empty chain.
- 
-   const BranchProbability ColdProb(1, 5); // 20%
--  BlockFrequency EntryFreq = MBFI->getBlockFreq(F.begin());
-+  BlockFrequency EntryFreq = MBFI->getBlockFreq(&F.front());
-   BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
-   for (BlockChain::iterator BI = std::next(FunctionChain.begin()),
-                             BE = FunctionChain.end();
-@@ -1182,7 +1181,7 @@
-   MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
- 
-   for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) {
--    BlockFrequency BlockFreq = MBFI->getBlockFreq(I);
-+    BlockFrequency BlockFreq = MBFI->getBlockFreq(&*I);
-     Statistic &NumBranches = (I->succ_size() > 1) ? NumCondBranches
-                                                   : NumUncondBranches;
-     Statistic &BranchTakenFreq = (I->succ_size() > 1) ? CondBranchTakenFreq
-@@ -1194,7 +1193,8 @@
-       if (I->isLayoutSuccessor(*SI))
-         continue;
- 
--      BlockFrequency EdgeFreq = BlockFreq * MBPI->getEdgeProbability(I, *SI);
-+      BlockFrequency EdgeFreq =
-+        BlockFreq * MBPI->getEdgeProbability(&*I, *SI);
-       ++NumBranches;
-       BranchTakenFreq += EdgeFreq.getFrequency();
-     }
---- lib/CodeGen/MachineFunction.cpp	2015-01-12 16:48:10.000000000 -0800
-+++ lib/CodeGen/MachineFunction.cpp	2015-12-06 20:48:05.529036618 -0800
-@@ -144,7 +144,7 @@
-   if (MBB == nullptr)
-     MBBI = begin();
-   else
--    MBBI = MBB;
-+    MBBI = MBB->getIterator();
- 
-   // Figure out the block number this should have.
-   unsigned BlockNo = 0;
-@@ -164,7 +164,7 @@
-       if (MBBNumbering[BlockNo])
-         MBBNumbering[BlockNo]->setNumber(-1);
- 
--      MBBNumbering[BlockNo] = MBBI;
-+      MBBNumbering[BlockNo] = &*MBBI;
-       MBBI->setNumber(BlockNo);
-     }
-   }
---- lib/CodeGen/MachineInstr.cpp	2014-12-09 10:38:53.000000000 -0800
-+++ lib/CodeGen/MachineInstr.cpp	2015-12-06 21:23:40.823649137 -0800
-@@ -825,7 +825,8 @@
- 
- bool MachineInstr::hasPropertyInBundle(unsigned Mask, QueryType Type) const {
-   assert(!isBundledWithPred() && "Must be called on bundle header");
--  for (MachineBasicBlock::const_instr_iterator MII = this;; ++MII) {
-+  for (MachineBasicBlock::const_instr_iterator MII = getIterator();
-+       /* empty */ ; ++MII) {
-     if (MII->getDesc().getFlags() & Mask) {
-       if (Type == AnyInBundle)
-         return true;
-@@ -849,13 +850,13 @@
- 
-   if (isBundle()) {
-     // Both instructions are bundles, compare MIs inside the bundle.
--    MachineBasicBlock::const_instr_iterator I1 = *this;
-+    MachineBasicBlock::const_instr_iterator I1 = getIterator();
-     MachineBasicBlock::const_instr_iterator E1 = getParent()->instr_end();
--    MachineBasicBlock::const_instr_iterator I2 = *Other;
-+    MachineBasicBlock::const_instr_iterator I2 = Other->getIterator();
-     MachineBasicBlock::const_instr_iterator E2= Other->getParent()->instr_end();
-     while (++I1 != E1 && I1->isInsideBundle()) {
-       ++I2;
--      if (I2 == E2 || !I2->isInsideBundle() || !I1->isIdenticalTo(I2, Check))
-+      if (I2 == E2 || !I2->isInsideBundle() || !I1->isIdenticalTo(&*I2, Check))
-         return false;
-     }
-   }
-@@ -961,7 +962,7 @@
- void MachineInstr::bundleWithPred() {
-   assert(!isBundledWithPred() && "MI is already bundled with its predecessor");
-   setFlag(BundledPred);
--  MachineBasicBlock::instr_iterator Pred = this;
-+  MachineBasicBlock::instr_iterator Pred = getIterator();
-   --Pred;
-   assert(!Pred->isBundledWithSucc() && "Inconsistent bundle flags");
-   Pred->setFlag(BundledSucc);
-@@ -970,7 +971,7 @@
- void MachineInstr::bundleWithSucc() {
-   assert(!isBundledWithSucc() && "MI is already bundled with its successor");
-   setFlag(BundledSucc);
--  MachineBasicBlock::instr_iterator Succ = this;
-+  MachineBasicBlock::instr_iterator Succ = getIterator();
-   ++Succ;
-   assert(!Succ->isBundledWithPred() && "Inconsistent bundle flags");
-   Succ->setFlag(BundledPred);
-@@ -979,7 +980,7 @@
- void MachineInstr::unbundleFromPred() {
-   assert(isBundledWithPred() && "MI isn't bundled with its predecessor");
-   clearFlag(BundledPred);
--  MachineBasicBlock::instr_iterator Pred = this;
-+  MachineBasicBlock::instr_iterator Pred = getIterator();
-   --Pred;
-   assert(Pred->isBundledWithSucc() && "Inconsistent bundle flags");
-   Pred->clearFlag(BundledSucc);
-@@ -988,7 +989,7 @@
- void MachineInstr::unbundleFromSucc() {
-   assert(isBundledWithSucc() && "MI isn't bundled with its successor");
-   clearFlag(BundledSucc);
--  MachineBasicBlock::instr_iterator Succ = this;
-+  MachineBasicBlock::instr_iterator Succ = getIterator();
-   ++Succ;
-   assert(Succ->isBundledWithPred() && "Inconsistent bundle flags");
-   Succ->clearFlag(BundledPred);
-@@ -1125,7 +1126,7 @@
- /// Return the number of instructions inside the MI bundle, not counting the
- /// header instruction.
- unsigned MachineInstr::getBundleSize() const {
--  MachineBasicBlock::const_instr_iterator I = this;
-+  MachineBasicBlock::const_instr_iterator I = getIterator();
-   unsigned Size = 0;
-   while (I->isBundledWithSucc())
-     ++Size, ++I;
---- lib/CodeGen/MachineLoopInfo.cpp	2014-03-02 04:27:27.000000000 -0800
-+++ lib/CodeGen/MachineLoopInfo.cpp	2015-12-06 21:26:39.722845395 -0800
-@@ -50,11 +50,11 @@
-   MachineBasicBlock *TopMBB = getHeader();
-   MachineFunction::iterator Begin = TopMBB->getParent()->begin();
-   if (TopMBB != Begin) {
--    MachineBasicBlock *PriorMBB = std::prev(MachineFunction::iterator(TopMBB));
-+    MachineBasicBlock *PriorMBB = &*std::prev(TopMBB->getIterator());
-     while (contains(PriorMBB)) {
-       TopMBB = PriorMBB;
-       if (TopMBB == Begin) break;
--      PriorMBB = std::prev(MachineFunction::iterator(TopMBB));
-+      PriorMBB = &*std::prev(TopMBB->getIterator());
-     }
-   }
-   return TopMBB;
-@@ -64,11 +64,11 @@
-   MachineBasicBlock *BotMBB = getHeader();
-   MachineFunction::iterator End = BotMBB->getParent()->end();
-   if (BotMBB != std::prev(End)) {
--    MachineBasicBlock *NextMBB = std::next(MachineFunction::iterator(BotMBB));
-+    MachineBasicBlock *NextMBB = &*std::next(BotMBB->getIterator());
-     while (contains(NextMBB)) {
-       BotMBB = NextMBB;
-       if (BotMBB == std::next(MachineFunction::iterator(BotMBB))) break;
--      NextMBB = std::next(MachineFunction::iterator(BotMBB));
-+      NextMBB = &*std::next(BotMBB->getIterator());
-     }
-   }
-   return BotMBB;
---- lib/CodeGen/MachineScheduler.cpp	2014-12-12 20:52:04.000000000 -0800
-+++ lib/CodeGen/MachineScheduler.cpp	2015-12-06 21:37:05.936122225 -0800
-@@ -391,7 +391,7 @@
-   for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
-        MBB != MBBEnd; ++MBB) {
- 
--    Scheduler.startBlock(MBB);
-+    Scheduler.startBlock(&*MBB);
- 
- #ifndef NDEBUG
-     if (SchedOnlyFunc.getNumOccurrences() && SchedOnlyFunc != MF->getName())
-@@ -420,7 +420,7 @@
- 
-       // Avoid decrementing RegionEnd for blocks with no terminator.
-       if (RegionEnd != MBB->end() ||
--          isSchedBoundary(std::prev(RegionEnd), MBB, MF, TII, IsPostRA)) {
-+          isSchedBoundary(std::prev(RegionEnd), &*MBB, MF, TII, IsPostRA)) {
-         --RegionEnd;
-         // Count the boundary instruction.
-         --RemainingInstrs;
-@@ -431,14 +431,14 @@
-       unsigned NumRegionInstrs = 0;
-       MachineBasicBlock::iterator I = RegionEnd;
-       for(;I != MBB->begin(); --I, --RemainingInstrs) {
--        if (isSchedBoundary(std::prev(I), MBB, MF, TII, IsPostRA))
-+        if (isSchedBoundary(std::prev(I), &*MBB, MF, TII, IsPostRA))
-           break;
-         if (!I->isDebugValue())
-           ++NumRegionInstrs;
-       }
-       // Notify the scheduler of the region, even if we may skip scheduling
-       // it. Perhaps it still needs to be bundled.
--      Scheduler.enterRegion(MBB, I, RegionEnd, NumRegionInstrs);
-+      Scheduler.enterRegion(&*MBB, I, RegionEnd, NumRegionInstrs);
- 
-       // Skip empty scheduling regions (0 or 1 schedulable instructions).
-       if (I == RegionEnd || I == std::prev(RegionEnd)) {
-@@ -478,7 +478,7 @@
-     if (Scheduler.isPostRA()) {
-       // FIXME: Ideally, no further passes should rely on kill flags. However,
-       // thumb2 size reduction is currently an exception.
--      Scheduler.fixupKills(MBB);
-+      Scheduler.fixupKills(&*MBB);
-     }
-   }
-   Scheduler.finalizeSchedule();
---- lib/CodeGen/MachineVerifier.cpp	2014-12-11 11:41:51.000000000 -0800
-+++ lib/CodeGen/MachineVerifier.cpp	2015-12-06 22:06:08.770556953 -0800
-@@ -317,7 +317,7 @@
-   visitMachineFunctionBefore();
-   for (MachineFunction::const_iterator MFI = MF.begin(), MFE = MF.end();
-        MFI!=MFE; ++MFI) {
--    visitMachineBasicBlockBefore(MFI);
-+    visitMachineBasicBlockBefore(&*MFI);
-     // Keep track of the current bundle header.
-     const MachineInstr *CurBundle = nullptr;
-     // Do we expect the next instruction to be part of the same bundle?
-@@ -325,8 +325,8 @@
- 
-     for (MachineBasicBlock::const_instr_iterator MBBI = MFI->instr_begin(),
-            MBBE = MFI->instr_end(); MBBI != MBBE; ++MBBI) {
--      if (MBBI->getParent() != MFI) {
--        report("Bad instruction parent pointer", MFI);
-+      if (MBBI->getParent() != &*MFI) {
-+        report("Bad instruction parent pointer", &*MFI);
-         *OS << "Instruction: " << *MBBI;
-         continue;
-       }
-@@ -334,33 +334,44 @@
-       // Check for consistent bundle flags.
-       if (InBundle && !MBBI->isBundledWithPred())
-         report("Missing BundledPred flag, "
--               "BundledSucc was set on predecessor", MBBI);
-+               "BundledSucc was set on predecessor", &*MBBI);
-       if (!InBundle && MBBI->isBundledWithPred())
-         report("BundledPred flag is set, "
--               "but BundledSucc not set on predecessor", MBBI);
-+               "but BundledSucc not set on predecessor", &*MBBI);
- 
-       // Is this a bundle header?
-       if (!MBBI->isInsideBundle()) {
-         if (CurBundle)
-           visitMachineBundleAfter(CurBundle);
--        CurBundle = MBBI;
-+        CurBundle = &*MBBI;
-         visitMachineBundleBefore(CurBundle);
-       } else if (!CurBundle)
--        report("No bundle header", MBBI);
--      visitMachineInstrBefore(MBBI);
--      for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I)
--        visitMachineOperand(&MBBI->getOperand(I), I);
--      visitMachineInstrAfter(MBBI);
-+        report("No bundle header", &*MBBI);
-+
-+      visitMachineInstrBefore(&*MBBI);
-+
-+      for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I) {
-+        const MachineInstr &MI = *MBBI;
-+        const MachineOperand &Op = MI.getOperand(I);
-+        if (Op.getParent() != &MI)
-+          report("Instruction has operand with wrong parent set", &MI);
-+
-+        visitMachineOperand(&Op, I);
-+      }
-+
-+      visitMachineInstrAfter(&*MBBI);
- 
-       // Was this the last bundled instruction?
-       InBundle = MBBI->isBundledWithSucc();
-     }
-+
-     if (CurBundle)
-       visitMachineBundleAfter(CurBundle);
-     if (InBundle)
-       report("BundledSucc flag set on last instruction in block", &MFI->back());
--    visitMachineBasicBlockAfter(MFI);
-+    visitMachineBasicBlockAfter(&*MFI);
-   }
-+
-   visitMachineFunctionAfter();
- 
-   if (OutFile)
-@@ -573,7 +584,7 @@
-     // check whether its answers match up with reality.
-     if (!TBB && !FBB) {
-       // Block falls through to its successor.
--      MachineFunction::const_iterator MBBI = MBB;
-+      MachineFunction::const_iterator MBBI = MBB->getIterator();
-       ++MBBI;
-       if (MBBI == MF->end()) {
-         // It's possible that the block legitimately ends with a noreturn
-@@ -586,7 +597,7 @@
-       } else if (MBB->succ_size() != 1+LandingPadSuccs.size()) {
-         report("MBB exits via unconditional fall-through but doesn't have "
-                "exactly one CFG successor!", MBB);
--      } else if (!MBB->isSuccessor(MBBI)) {
-+      } else if (!MBB->isSuccessor(&*MBBI)) {
-         report("MBB exits via unconditional fall-through but its successor "
-                "differs from its CFG successor!", MBB);
-       }
-@@ -624,7 +635,7 @@
-       }
-     } else if (TBB && !FBB && !Cond.empty()) {
-       // Block conditionally branches somewhere, otherwise falls through.
--      MachineFunction::const_iterator MBBI = MBB;
-+      MachineFunction::const_iterator MBBI = MBB->getIterator();
-       ++MBBI;
-       if (MBBI == MF->end()) {
-         report("MBB conditionally falls through out of function!", MBB);
-@@ -639,7 +650,7 @@
-       } else if (MBB->succ_size() != 2) {
-         report("MBB exits via conditional branch/fall-through but doesn't have "
-                "exactly two CFG successors!", MBB);
--      } else if (!matchPair(MBB->succ_begin(), TBB, MBBI)) {
-+      } else if (!matchPair(MBB->succ_begin(), TBB, &*MBBI)) {
-         report("MBB exits via conditional branch/fall-through but the CFG "
-                "successors don't match the actual successors!", MBB);
-       }
-@@ -1585,7 +1596,7 @@
-   }
- 
-   // Now check all the basic blocks in this live segment.
--  MachineFunction::const_iterator MFI = MBB;
-+  MachineFunction::const_iterator MFI = MBB->getIterator();
-   // Is this live segment the beginning of a non-PHIDef VN?
-   if (S.start == VNI->def && !VNI->isPHIDef()) {
-     // Not live-in to any blocks.
-@@ -1595,7 +1606,7 @@
-     ++MFI;
-   }
-   for (;;) {
--    assert(LiveInts->isLiveInToMBB(LR, MFI));
-+    assert(LiveInts->isLiveInToMBB(LR, &*MFI));
-     // We don't know how to track physregs into a landing pad.
-     if (!TargetRegisterInfo::isVirtualRegister(Reg) &&
-         MFI->isLandingPad()) {
-@@ -1607,7 +1618,7 @@
- 
-     // Is VNI a PHI-def in the current block?
-     bool IsPHI = VNI->isPHIDef() &&
--      VNI->def == LiveInts->getMBBStartIdx(MFI);
-+      VNI->def == LiveInts->getMBBStartIdx(&*MFI);
- 
-     // Check that VNI is live-out of all predecessors.
-     for (MachineBasicBlock::const_pred_iterator PI = MFI->pred_begin(),
-@@ -1620,7 +1631,7 @@
-         report("Register not marked live out of predecessor", *PI, LR, Reg,
-                LaneMask);
-         *OS << "Valno #" << VNI->id << " live into BB#" << MFI->getNumber()
--            << '@' << LiveInts->getMBBStartIdx(MFI) << ", not live before "
-+            << '@' << LiveInts->getMBBStartIdx(&*MFI) << ", not live before "
-             << PEnd << '\n';
-         continue;
-       }
-@@ -1632,7 +1643,7 @@
-         *OS << "Valno #" << PVNI->id << " live out of BB#"
-             << (*PI)->getNumber() << '@' << PEnd
-             << "\nValno #" << VNI->id << " live into BB#" << MFI->getNumber()
--            << '@' << LiveInts->getMBBStartIdx(MFI) << '\n';
-+            << '@' << LiveInts->getMBBStartIdx(&*MFI) << '\n';
-       }
-     }
-     if (&*MFI == EndMBB)
---- lib/CodeGen/Passes.cpp	2015-02-11 16:29:01.000000000 -0800
-+++ lib/CodeGen/Passes.cpp	2016-01-23 20:25:56.000000000 -0800
-@@ -83,10 +83,13 @@
- static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
-     cl::desc("Verify generated machine code"),
-     cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=nullptr));
-+
-+static std::string PMIInitString("option-unspecified");
- static cl::opt<std::string>
- PrintMachineInstrs("print-machineinstrs", cl::ValueOptional,
-                    cl::desc("Print machine instrs"),
--                   cl::value_desc("pass-name"), cl::init("option-unspecified"));
-+                   cl::value_desc("pass-name"),
-+                   cl::init(PMIInitString));
- 
- // Temporary option to allow experimenting with MachineScheduler as a post-RA
- // scheduler. Targets can "properly" enable this with
---- lib/CodeGen/PostRASchedulerList.cpp	2014-10-29 08:23:11.000000000 -0700
-+++ lib/CodeGen/PostRASchedulerList.cpp	2016-01-23 20:26:45.000000000 -0800
-@@ -58,11 +58,13 @@
- EnablePostRAScheduler("post-RA-scheduler",
-                        cl::desc("Enable scheduling after register allocation"),
-                        cl::init(false), cl::Hidden);
-+
-+static std::string NoneString("none");
- static cl::opt<std::string>
- EnableAntiDepBreaking("break-anti-dependencies",
-                       cl::desc("Break post-RA scheduling anti-dependencies: "
-                                "\"critical\", \"all\", or \"none\""),
--                      cl::init("none"), cl::Hidden);
-+                      cl::init(NoneString), cl::Hidden);
- 
- // If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
- static cl::opt<int>
-@@ -318,7 +320,7 @@
- #endif
- 
-     // Initialize register live-range state for scheduling in this block.
--    Scheduler.startBlock(MBB);
-+    Scheduler.startBlock(&*MBB);
- 
-     // Schedule each sequence of instructions not interrupted by a label
-     // or anything else that effectively needs to shut down scheduling.
-@@ -330,8 +332,8 @@
-       // Calls are not scheduling boundaries before register allocation, but
-       // post-ra we don't gain anything by scheduling across calls since we
-       // don't need to worry about register pressure.
--      if (MI->isCall() || TII->isSchedulingBoundary(MI, MBB, Fn)) {
--        Scheduler.enterRegion(MBB, I, Current, CurrentCount - Count);
-+      if (MI->isCall() || TII->isSchedulingBoundary(MI, &*MBB, Fn)) {
-+        Scheduler.enterRegion(&*MBB, I, Current, CurrentCount - Count);
-         Scheduler.setEndIndex(CurrentCount);
-         Scheduler.schedule();
-         Scheduler.exitRegion();
-@@ -347,7 +349,7 @@
-     assert(Count == 0 && "Instruction count mismatch!");
-     assert((MBB->begin() == Current || CurrentCount != 0) &&
-            "Instruction count mismatch!");
--    Scheduler.enterRegion(MBB, MBB->begin(), Current, CurrentCount);
-+    Scheduler.enterRegion(&*MBB, MBB->begin(), Current, CurrentCount);
-     Scheduler.setEndIndex(CurrentCount);
-     Scheduler.schedule();
-     Scheduler.exitRegion();
-@@ -357,7 +359,7 @@
-     Scheduler.finishBlock();
- 
-     // Update register kills
--    Scheduler.fixupKills(MBB);
-+    Scheduler.fixupKills(&*MBB);
-   }
- 
-   return true;
---- lib/CodeGen/ProcessImplicitDefs.cpp	2014-08-04 19:39:49.000000000 -0700
-+++ lib/CodeGen/ProcessImplicitDefs.cpp	2015-12-07 06:32:25.399048598 -0800
-@@ -96,11 +96,11 @@
- 
-   // This is a physreg implicit-def.
-   // Look for the first instruction to use or define an alias.
--  MachineBasicBlock::instr_iterator UserMI = MI;
-+  MachineBasicBlock::instr_iterator UserMI = MI->getIterator();
-   MachineBasicBlock::instr_iterator UserE = MI->getParent()->instr_end();
-   bool Found = false;
-   for (++UserMI; UserMI != UserE; ++UserMI) {
--    for (MIOperands MO(UserMI); MO.isValid(); ++MO) {
-+    for (MIOperands MO(&*UserMI); MO.isValid(); ++MO) {
-       if (!MO->isReg())
-         continue;
-       unsigned UserReg = MO->getReg();
-@@ -151,7 +151,7 @@
-     for (MachineBasicBlock::instr_iterator MBBI = MFI->instr_begin(),
-          MBBE = MFI->instr_end(); MBBI != MBBE; ++MBBI)
-       if (MBBI->isImplicitDef())
--        WorkList.insert(MBBI);
-+        WorkList.insert(&*MBBI);
- 
-     if (WorkList.empty())
-       continue;
---- lib/CodeGen/PrologEpilogInserter.cpp	2015-01-12 16:48:10.000000000 -0800
-+++ lib/CodeGen/PrologEpilogInserter.cpp	2015-12-07 06:37:25.905435777 -0800
-@@ -94,13 +94,11 @@
-     return;
- 
-   // Save refs to entry and return blocks.
--  EntryBlock = Fn.begin();
--  for (MachineFunction::iterator MBB = Fn.begin(), E = Fn.end();
--       MBB != E; ++MBB)
--    if (isReturnBlock(MBB))
--      ReturnBlocks.push_back(MBB);
--
--  return;
-+  EntryBlock = &Fn.front();
-+  for (MachineBasicBlock &MBB : Fn) {
-+    if (isReturnBlock(&MBB))
-+      ReturnBlocks.push_back(&MBB);
-+  }
- }
- 
- /// StackObjSet - A set of stack object indexes
-@@ -728,11 +726,11 @@
- 
-   // Handle the unreachable blocks.
-   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
--    if (Reachable.count(BB))
-+    if (Reachable.count(&*BB))
-       // Already handled in DFS traversal.
-       continue;
-     int SPAdj = 0;
--    replaceFrameIndices(BB, Fn, SPAdj);
-+    replaceFrameIndices(&*BB, Fn, SPAdj);
-   }
- }
- 
-@@ -873,7 +871,7 @@
-   // Run through the instructions and find any virtual registers.
-   for (MachineFunction::iterator BB = Fn.begin(),
-        E = Fn.end(); BB != E; ++BB) {
--    RS->enterBasicBlock(BB);
-+    RS->enterBasicBlock(&*BB);
- 
-     int SPAdj = 0;
- 
-@@ -922,7 +920,7 @@
-           assert (ScratchReg && "Missing scratch register!");
-           MachineRegisterInfo &MRI = Fn.getRegInfo();
-           Fn.getRegInfo().replaceRegWith(Reg, ScratchReg);
--          
-+
-           // Make sure MRI now accounts this register as used.
-           MRI.setPhysRegUsed(ScratchReg);
- 
-@@ -938,7 +936,7 @@
-       // problem because we need the spill code before I: Move I to just
-       // prior to J.
-       if (I != std::prev(J)) {
--        BB->splice(J, BB, I);
-+        BB->splice(J, &*BB, I);
- 
-         // Before we move I, we need to prepare the RS to visit I again.
-         // Specifically, RS will assert if it sees uses of registers that
---- lib/CodeGen/RegisterCoalescer.cpp	2015-01-14 03:23:27.000000000 -0800
-+++ lib/CodeGen/RegisterCoalescer.cpp	2015-12-07 06:39:22.414657202 -0800
-@@ -2669,7 +2669,7 @@
-   std::vector<MBBPriorityInfo> MBBs;
-   MBBs.reserve(MF->size());
-   for (MachineFunction::iterator I = MF->begin(), E = MF->end();I != E;++I){
--    MachineBasicBlock *MBB = I;
-+    MachineBasicBlock *MBB = &*I;
-     MBBs.push_back(MBBPriorityInfo(MBB, Loops->getLoopDepth(MBB),
-                                    JoinSplitEdges && isSplitEdge(MBB)));
-   }
---- lib/CodeGen/SelectionDAG/DAGCombiner.cpp	2015-04-01 17:15:35.000000000 -0700
-+++ lib/CodeGen/SelectionDAG/DAGCombiner.cpp	2015-12-07 08:35:37.075981457 -0800
-@@ -1163,7 +1163,7 @@
-   // Add all the dag nodes to the worklist.
-   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
-        E = DAG.allnodes_end(); I != E; ++I)
--    AddToWorklist(I);
-+    AddToWorklist(&*I);
- 
-   // Create a dummy node (which is not added to allnodes), that adds a reference
-   // to the root node, preventing it from being deleted, and tracking any
---- lib/CodeGen/SelectionDAG/FastISel.cpp	2015-04-29 07:54:57.000000000 -0700
-+++ lib/CodeGen/SelectionDAG/FastISel.cpp	2015-12-07 08:37:53.997786920 -0800
-@@ -116,9 +116,9 @@
-   for (Function::const_arg_iterator I = FuncInfo.Fn->arg_begin(),
-                                     E = FuncInfo.Fn->arg_end();
-        I != E; ++I) {
--    DenseMap<const Value *, unsigned>::iterator VI = LocalValueMap.find(I);
-+    DenseMap<const Value *, unsigned>::iterator VI = LocalValueMap.find(&*I);
-     assert(VI != LocalValueMap.end() && "Missed an argument?");
--    FuncInfo.ValueMap[I] = VI->second;
-+    FuncInfo.ValueMap[&*I] = VI->second;
-   }
-   return true;
- }
---- lib/CodeGen/SelectionDAG/FunctionLoweringInfo.cpp	2014-12-02 10:50:36.000000000 -0800
-+++ lib/CodeGen/SelectionDAG/FunctionLoweringInfo.cpp	2015-12-07 08:44:06.691399075 -0800
-@@ -130,7 +130,7 @@
- 
-       // Look for inline asm that clobbers the SP register.
-       if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
--        ImmutableCallSite CS(I);
-+        ImmutableCallSite CS(&*I);
-         if (isa<InlineAsm>(CS.getCalledValue())) {
-           unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
-           std::vector<TargetLowering::AsmOperandInfo> Ops =
-@@ -167,10 +167,10 @@
- 
-       // Mark values used outside their block as exported, by allocating
-       // a virtual register for them.
--      if (isUsedOutsideOfDefiningBlock(I))
-+      if (isUsedOutsideOfDefiningBlock(&*I))
-         if (!isa<AllocaInst>(I) ||
-             !StaticAllocaMap.count(cast<AllocaInst>(I)))
--          InitializeRegForValue(I);
-+          InitializeRegForValue(&*I);
- 
-       // Collect llvm.dbg.declare information. This is done now instead of
-       // during the initial isel pass through the IR so that it is done
-@@ -204,15 +204,15 @@
-       }
- 
-       // Decide the preferred extend type for a value.
--      PreferredExtendType[I] = getPreferredExtendForValue(I);
-+      PreferredExtendType[&*I] = getPreferredExtendForValue(&*I);
-     }
- 
-   // Create an initial MachineBasicBlock for each LLVM BasicBlock in F.  This
-   // also creates the initial PHI MachineInstrs, though none of the input
-   // operands are populated.
-   for (BB = Fn->begin(); BB != EB; ++BB) {
--    MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
--    MBBMap[BB] = MBB;
-+    MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(&*BB);
-+    MBBMap[&*BB] = MBB;
-     MF->push_back(MBB);
- 
-     // Transfer the address-taken flag. This is necessary because there could
---- lib/CodeGen/SelectionDAG/LegalizeDAG.cpp	2015-01-13 17:35:17.000000000 -0800
-+++ lib/CodeGen/SelectionDAG/LegalizeDAG.cpp	2015-12-07 08:49:07.697376637 -0800
-@@ -4326,7 +4326,7 @@
-     for (auto NI = allnodes_end(); NI != allnodes_begin();) {
-       --NI;
- 
--      SDNode *N = NI;
-+      SDNode *N = &*NI;
-       if (N->use_empty() && N != getRoot().getNode()) {
-         ++NI;
-         DeleteNode(N);
---- lib/CodeGen/SelectionDAG/LegalizeTypes.cpp	2014-12-02 14:01:00.000000000 -0800
-+++ lib/CodeGen/SelectionDAG/LegalizeTypes.cpp	2015-12-07 08:56:21.562944470 -0800
-@@ -77,10 +77,10 @@
-        E = DAG.allnodes_end(); I != E; ++I) {
-     // Remember nodes marked NewNode - they are subject to extra checking below.
-     if (I->getNodeId() == NewNode)
--      NewNodes.push_back(I);
-+      NewNodes.push_back(&*I);
- 
-     for (unsigned i = 0, e = I->getNumValues(); i != e; ++i) {
--      SDValue Res(I, i);
-+      SDValue Res(&*I, i);
-       bool Failed = false;
- 
-       unsigned Mapped = 0;
-@@ -128,7 +128,7 @@
-           dbgs() << "Unprocessed value in a map!";
-           Failed = true;
-         }
--      } else if (isTypeLegal(Res.getValueType()) || IgnoreNodeResults(I)) {
-+      } else if (isTypeLegal(Res.getValueType()) || IgnoreNodeResults(&*I)) {
-         if (Mapped > 1) {
-           dbgs() << "Value with legal type was transformed!";
-           Failed = true;
-@@ -198,7 +198,7 @@
-        E = DAG.allnodes_end(); I != E; ++I) {
-     if (I->getNumOperands() == 0) {
-       I->setNodeId(ReadyToProcess);
--      Worklist.push_back(I);
-+      Worklist.push_back(&*I);
-     } else {
-       I->setNodeId(Unanalyzed);
-     }
-@@ -406,7 +406,7 @@
-     bool Failed = false;
- 
-     // Check that all result types are legal.
--    if (!IgnoreNodeResults(I))
-+    if (!IgnoreNodeResults(&*I))
-       for (unsigned i = 0, NumVals = I->getNumValues(); i < NumVals; ++i)
-         if (!isTypeLegal(I->getValueType(i))) {
-           dbgs() << "Result type " << i << " illegal!\n";
---- lib/CodeGen/SelectionDAG/LegalizeVectorOps.cpp	2015-02-12 15:51:24.000000000 -0800
-+++ lib/CodeGen/SelectionDAG/LegalizeVectorOps.cpp	2015-12-07 09:08:20.015507523 -0800
-@@ -159,7 +159,7 @@
-   DAG.AssignTopologicalOrder();
-   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
-        E = std::prev(DAG.allnodes_end()); I != std::next(E); ++I)
--    LegalizeOp(SDValue(I, 0));
-+    LegalizeOp(SDValue(&*I, 0));
- 
-   // Finally, it's possible the root changed.  Get the new root.
-   SDValue OldRoot = DAG.getRoot();
---- lib/CodeGen/SelectionDAG/ScheduleDAGFast.cpp	2014-11-18 23:49:26.000000000 -0800
-+++ lib/CodeGen/SelectionDAG/ScheduleDAGFast.cpp	2015-12-07 09:09:27.427273648 -0800
-@@ -728,7 +728,7 @@
-   unsigned DAGSize = 0;
-   for (SelectionDAG::allnodes_iterator I = DAG->allnodes_begin(),
-          E = DAG->allnodes_end(); I != E; ++I) {
--    SDNode *N = I;
-+    SDNode *N = &*I;
- 
-     // Use node id to record degree.
-     unsigned Degree = N->use_size();
---- lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp	2015-05-08 07:13:47.000000000 -0700
-+++ lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp	2015-12-07 10:48:44.168405053 -0800
-@@ -1460,7 +1460,7 @@
-   }
- 
-   //  Create TmpBB after CurBB.
--  MachineFunction::iterator BBI = CurBB;
-+  MachineFunction::iterator BBI(CurBB);
-   MachineFunction &MF = DAG.getMachineFunction();
-   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
-   CurBB->getParent()->insert(++BBI, TmpBB);
-@@ -1575,9 +1575,9 @@
- 
-   // Figure out which block is immediately after the current one.
-   MachineBasicBlock *NextBlock = nullptr;
--  MachineFunction::iterator BBI = BrMBB;
-+  MachineFunction::iterator BBI(BrMBB);
-   if (++BBI != FuncInfo.MF->end())
--    NextBlock = BBI;
-+    NextBlock = &*BBI;
- 
-   if (I.isUnconditional()) {
-     // Update machine-CFG edges.
-@@ -1708,9 +1708,9 @@
-   // Set NextBlock to be the MBB immediately after the current one, if any.
-   // This is used to avoid emitting unnecessary branches to the next block.
-   MachineBasicBlock *NextBlock = nullptr;
--  MachineFunction::iterator BBI = SwitchBB;
-+  MachineFunction::iterator BBI(SwitchBB);
-   if (++BBI != FuncInfo.MF->end())
--    NextBlock = BBI;
-+    NextBlock = &*BBI;
- 
-   // If the lhs block is the next block, invert the condition so that we can
-   // fall through to the lhs instead of the rhs block.
-@@ -1784,10 +1784,10 @@
-   // Set NextBlock to be the MBB immediately after the current one, if any.
-   // This is used to avoid emitting unnecessary branches to the next block.
-   MachineBasicBlock *NextBlock = nullptr;
--  MachineFunction::iterator BBI = SwitchBB;
-+  MachineFunction::iterator BBI(SwitchBB);
- 
-   if (++BBI != FuncInfo.MF->end())
--    NextBlock = BBI;
-+    NextBlock = &*BBI;
- 
-   SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
-                                MVT::Other, CopyTo, CMP,
-@@ -1925,9 +1925,9 @@
-   // Set NextBlock to be the MBB immediately after the current one, if any.
-   // This is used to avoid emitting unnecessary branches to the next block.
-   MachineBasicBlock *NextBlock = nullptr;
--  MachineFunction::iterator BBI = SwitchBB;
-+  MachineFunction::iterator BBI(SwitchBB);
-   if (++BBI != FuncInfo.MF->end())
--    NextBlock = BBI;
-+    NextBlock = &*BBI;
- 
-   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
- 
-@@ -1994,9 +1994,9 @@
-   // Set NextBlock to be the MBB immediately after the current one, if any.
-   // This is used to avoid emitting unnecessary branches to the next block.
-   MachineBasicBlock *NextBlock = nullptr;
--  MachineFunction::iterator BBI = SwitchBB;
-+  MachineFunction::iterator BBI(SwitchBB);
-   if (++BBI != FuncInfo.MF->end())
--    NextBlock = BBI;
-+    NextBlock = &*BBI;
- 
-   if (NextMBB != NextBlock)
-     BrAnd = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrAnd,
-@@ -2104,10 +2104,10 @@
- 
-   // Figure out which block is immediately after the current one.
-   MachineBasicBlock *NextBlock = nullptr;
--  MachineFunction::iterator BBI = CR.CaseBB;
-+  MachineFunction::iterator BBI(CR.CaseBB);
- 
-   if (++BBI != FuncInfo.MF->end())
--    NextBlock = BBI;
-+    NextBlock = &*BBI;
- 
-   BranchProbabilityInfo *BPI = FuncInfo.BPI;
-   // If any two of the cases has the same destination, and if one value
-@@ -2291,7 +2291,7 @@
-   MachineFunction *CurMF = FuncInfo.MF;
- 
-   // Figure out which block is immediately after the current one.
--  MachineFunction::iterator BBI = CR.CaseBB;
-+  MachineFunction::iterator BBI(CR.CaseBB);
-   ++BBI;
- 
-   const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
-@@ -2377,7 +2377,7 @@
-   MachineFunction *CurMF = FuncInfo.MF;
- 
-   // Figure out which block is immediately after the current one.
--  MachineFunction::iterator BBI = CR.CaseBB;
-+  MachineFunction::iterator BBI(CR.CaseBB);
-   ++BBI;
- 
-   Case& FrontCase = *CR.Range.first;
-@@ -2600,7 +2600,7 @@
-   BitTestInfo BTC;
- 
-   // Figure out which block is immediately after the current one.
--  MachineFunction::iterator BBI = CR.CaseBB;
-+  MachineFunction::iterator BBI(CR.CaseBB);
-   ++BBI;
- 
-   const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
-@@ -7614,7 +7614,7 @@
-   if (FastISel)
-     return A->use_empty();
- 
--  const BasicBlock *Entry = A->getParent()->begin();
-+  const BasicBlock *Entry = &A->getParent()->front();
-   for (const User *U : A->users())
-     if (cast<Instruction>(U)->getParent() != Entry || isa<SwitchInst>(U))
-       return false;  // Use not in entry block.
-@@ -7779,12 +7779,12 @@
-     // If this argument is unused then remember its value. It is used to generate
-     // debugging information.
-     if (I->use_empty() && NumValues) {
--      SDB->setUnusedArgValue(I, InVals[i]);
-+      SDB->setUnusedArgValue(&*I, InVals[i]);
- 
-       // Also remember any frame index for use in FastISel.
-       if (FrameIndexSDNode *FI =
-           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
--        FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
-+        FuncInfo->setArgumentFrameIndex(&*I, FI->getIndex());
-     }
- 
-     for (unsigned Val = 0; Val != NumValues; ++Val) {
-@@ -7814,18 +7814,18 @@
-     // Note down frame index.
-     if (FrameIndexSDNode *FI =
-         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
--      FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
-+      FuncInfo->setArgumentFrameIndex(&*I, FI->getIndex());
- 
-     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
-                                      SDB->getCurSDLoc());
- 
--    SDB->setValue(I, Res);
-+    SDB->setValue(&*I, Res);
-     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
-       if (LoadSDNode *LNode =
-           dyn_cast<LoadSDNode>(Res.getOperand(0).getNode()))
-         if (FrameIndexSDNode *FI =
-             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
--        FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
-+        FuncInfo->setArgumentFrameIndex(&*I, FI->getIndex());
-     }
- 
-     // If this argument is live outside of the entry block, insert a copy from
-@@ -7837,13 +7837,13 @@
-       // uses with vregs.
-       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
-       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
--        FuncInfo->ValueMap[I] = Reg;
-+        FuncInfo->ValueMap[&*I] = Reg;
-         continue;
-       }
-     }
--    if (!isOnlyUsedInEntryBlock(I, TM.Options.EnableFastISel)) {
--      FuncInfo->InitializeRegForValue(I);
--      SDB->CopyToExportRegsIfNeeded(I);
-+    if (!isOnlyUsedInEntryBlock(&*I, TM.Options.EnableFastISel)) {
-+      FuncInfo->InitializeRegForValue(&*I);
-+      SDB->CopyToExportRegsIfNeeded(&*I);
-     }
-   }
- 
-@@ -7946,7 +7946,7 @@
-   // If SuccBB has not been created yet, create it.
-   if (!SuccMBB) {
-     MachineFunction *MF = ParentMBB->getParent();
--    MachineFunction::iterator BBI = ParentMBB;
-+    MachineFunction::iterator BBI(ParentMBB);
-     SuccMBB = MF->CreateMachineBasicBlock(BB);
-     MF->insert(++BBI, SuccMBB);
-   }
---- lib/CodeGen/SelectionDAG/SelectionDAGDumper.cpp	2014-12-04 01:40:44.000000000 -0800
-+++ lib/CodeGen/SelectionDAG/SelectionDAGDumper.cpp	2015-12-07 11:02:44.434678105 -0800
-@@ -554,7 +554,7 @@
- 
-   for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
-        I != E; ++I) {
--    const SDNode *N = I;
-+    const SDNode *N = &*I;
-     if (!N->hasOneUse() && N != getRoot().getNode())
-       DumpNodes(N, 2, this);
-   }
---- lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp	2015-06-14 08:38:10.000000000 -0700
-+++ lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp	2015-12-07 11:43:29.120419077 -0800
-@@ -401,7 +401,7 @@
- 
-         // Okay, we have to split this edge.
-         SplitCriticalEdge(Pred->getTerminator(),
--                          GetSuccessorNumber(Pred, BB), SDISel, true);
-+                          GetSuccessorNumber(Pred, &*BB), SDISel, true);
-         goto ReprocessBlock;
-       }
-   }
-@@ -457,7 +457,7 @@
-   // If the first basic block in the function has live ins that need to be
-   // copied into vregs, emit the copies into the top of the block before
-   // emitting the code for the block.
--  MachineBasicBlock *EntryMBB = MF->begin();
-+  MachineBasicBlock *EntryMBB = &MF->front();
-   const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
-   RegInfo->EmitLiveInCopies(EntryMBB, TRI, *TII);
- 
-@@ -868,7 +868,7 @@
-     // graph) and preceding back toward the beginning (the entry
-     // node).
-     while (ISelPosition != CurDAG->allnodes_begin()) {
--      SDNode *Node = --ISelPosition;
-+      SDNode *Node = &*--ISelPosition;
-       // Skip dead nodes. DAGCombiner is expected to eliminate all dead nodes,
-       // but there are currently some corner cases that it misses. Also, this
-       // makes it theoretically possible to disable the DAGCombiner.
-@@ -1085,7 +1085,8 @@
-       FuncInfo->VisitedBBs.insert(LLVMBB);
-     }
- 
--    BasicBlock::const_iterator const Begin = LLVMBB->getFirstNonPHI();
-+    BasicBlock::const_iterator const Begin =
-+      LLVMBB->getFirstNonPHI()->getIterator();
-     BasicBlock::const_iterator const End = LLVMBB->end();
-     BasicBlock::const_iterator BI = End;
- 
-@@ -1133,7 +1134,7 @@
-       unsigned NumFastIselRemaining = std::distance(Begin, End);
-       // Do FastISel on as many instructions as possible.
-       for (; BI != Begin; --BI) {
--        const Instruction *Inst = std::prev(BI);
-+        const Instruction *Inst = &*std::prev(BI);
- 
-         // If we no longer require this instruction, skip it.
-         if (isFoldedOrDeadInstruction(Inst, FuncInfo)) {
-@@ -1154,7 +1155,7 @@
-           // Try to fold the load if so.
-           const Instruction *BeforeInst = Inst;
-           while (BeforeInst != Begin) {
--            BeforeInst = std::prev(BasicBlock::const_iterator(BeforeInst));
-+            BeforeInst = &*std::prev(BasicBlock::const_iterator(BeforeInst));
-             if (!isFoldedOrDeadInstruction(BeforeInst, FuncInfo))
-               break;
-           }
-@@ -1190,7 +1191,7 @@
- 
-           bool HadTailCall = false;
-           MachineBasicBlock::iterator SavedInsertPt = FuncInfo->InsertPt;
--          SelectBasicBlock(Inst, BI, HadTailCall);
-+          SelectBasicBlock(Inst->getIterator(), BI, HadTailCall);
- 
-           // If the call was emitted as a tail call, we're done with the block.
-           // We also need to delete any previously emitted instructions.
---- lib/CodeGen/SelectionDAG/SelectionDAG.cpp	2015-02-17 13:57:20.000000000 -0800
-+++ lib/CodeGen/SelectionDAG/SelectionDAG.cpp	2015-12-07 09:14:05.327228003 -0800
-@@ -618,7 +618,7 @@
-   // Add all obviously-dead nodes to the DeadNodes worklist.
-   for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
-     if (I->use_empty())
--      DeadNodes.push_back(I);
-+      DeadNodes.push_back(&*I);
- 
-   RemoveDeadNodes(DeadNodes);
- 
-@@ -937,7 +937,7 @@
-   assert(&*AllNodes.begin() == &EntryNode);
-   AllNodes.remove(AllNodes.begin());
-   while (!AllNodes.empty())
--    DeallocateNode(AllNodes.begin());
-+    DeallocateNode(&AllNodes.front());
- }
- 
- BinarySDNode *SelectionDAG::GetBinarySDNode(unsigned Opcode, SDLoc DL,
-@@ -6139,13 +6139,15 @@
-   // Node Id fields for nodes At SortedPos and after will contain the
-   // count of outstanding operands.
-   for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
--    SDNode *N = I++;
-+    SDNode *N = &*I;
-+    ++I;
-+
-     checkForCycles(N, this);
-     unsigned Degree = N->getNumOperands();
-     if (Degree == 0) {
-       // A node with no uses, add it to the result array immediately.
-       N->setNodeId(DAGSize++);
--      allnodes_iterator Q = N;
-+      allnodes_iterator Q(N);
-       if (Q != SortedPos)
-         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
-       assert(SortedPos != AllNodes.end() && "Overran node list");
-@@ -6159,7 +6161,7 @@
-   // Visit all the nodes. As we iterate, move nodes into sorted order,
-   // such that by the time the end is reached all nodes will be sorted.
-   for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I) {
--    SDNode *N = I;
-+    SDNode *N = &*I;
-     checkForCycles(N, this);
-     // N is in sorted position, so all its uses have one less operand
-     // that needs to be sorted.
-@@ -6183,7 +6185,7 @@
-     }
-     if (I == SortedPos) {
- #ifndef NDEBUG
--      SDNode *S = ++I;
-+      SDNode *S = &*++I;
-       dbgs() << "Overran sorted position:\n";
-       S->dumprFull(this); dbgs() << "\n";
-       dbgs() << "Checking if this is due to cycles\n";
---- lib/CodeGen/ShadowStackGC.cpp	2014-11-13 14:55:19.000000000 -0800
-+++ lib/CodeGen/ShadowStackGC.cpp	2015-12-07 06:47:52.372680302 -0800
-@@ -112,7 +112,8 @@
-       case 1:
-         // Find all 'return', 'resume', and 'unwind' instructions.
-         while (StateBB != StateE) {
--          BasicBlock *CurBB = StateBB++;
-+          BasicBlock *CurBB = &*StateBB;
-+          ++StateBB;
- 
-           // Branches and invokes do not escape, only unwind, resume, and return
-           // do.
-@@ -120,7 +121,7 @@
-           if (!isa<ReturnInst>(TI) && !isa<ResumeInst>(TI))
-             continue;
- 
--          Builder.SetInsertPoint(TI->getParent(), TI);
-+          Builder.SetInsertPoint(TI);
-           return &Builder;
-         }
- 
-@@ -164,7 +165,8 @@
-           // Split the basic block containing the function call.
-           BasicBlock *CallBB = CI->getParent();
-           BasicBlock *NewBB =
--            CallBB->splitBasicBlock(CI, CallBB->getName() + ".cont");
-+            CallBB->splitBasicBlock(CI->getIterator(),
-+                                    CallBB->getName() + ".cont");
- 
-           // Remove the unconditional branch inserted at the end of CallBB.
-           CallBB->getInstList().pop_back();
-@@ -184,7 +186,7 @@
-           delete CI;
-         }
- 
--        Builder.SetInsertPoint(RI->getParent(), RI);
-+        Builder.SetInsertPoint(RI);
-         return &Builder;
-       }
-     }
---- lib/CodeGen/SjLjEHPrepare.cpp	2014-11-18 23:49:26.000000000 -0800
-+++ lib/CodeGen/SjLjEHPrepare.cpp	2015-12-07 06:54:48.366220128 -0800
-@@ -174,8 +174,8 @@
-   // values and replace the LPI with that aggregate.
-   Type *LPadType = LPI->getType();
-   Value *LPadVal = UndefValue::get(LPadType);
--  IRBuilder<> Builder(
--      std::next(BasicBlock::iterator(cast<Instruction>(SelVal))));
-+  auto *SelI = cast<Instruction>(SelVal);
-+  IRBuilder<> Builder(SelI->getParent(), std::next(SelI->getIterator()));
-   LPadVal = Builder.CreateInsertValue(LPadVal, ExnVal, 0, "lpad.val");
-   LPadVal = Builder.CreateInsertValue(LPadVal, SelVal, 1, "lpad.val");
- 
-@@ -186,7 +186,7 @@
- /// it with all of the data that we know at this point.
- Value *SjLjEHPrepare::setupFunctionContext(Function &F,
-                                            ArrayRef<LandingPadInst *> LPads) {
--  BasicBlock *EntryBB = F.begin();
-+  BasicBlock *EntryBB = &F.front();
- 
-   // Create an alloca for the incoming jump buffer ptr and the new jump buffer
-   // that needs to be restored on all exits from the function. This is an alloca
-@@ -195,12 +195,13 @@
-   unsigned Align =
-       TLI->getDataLayout()->getPrefTypeAlignment(FunctionContextTy);
-   FuncCtx = new AllocaInst(FunctionContextTy, nullptr, Align, "fn_context",
--                           EntryBB->begin());
-+                           &EntryBB->front());
- 
-   // Fill in the function context structure.
-   for (unsigned I = 0, E = LPads.size(); I != E; ++I) {
-     LandingPadInst *LPI = LPads[I];
--    IRBuilder<> Builder(LPI->getParent()->getFirstInsertionPt());
-+    IRBuilder<> Builder(LPI->getParent(),
-+                        LPI->getParent()->getFirstInsertionPt());
- 
-     // Reference the __data field.
-     Value *FCData = Builder.CreateConstGEP2_32(FuncCtx, 0, 2, "__data");
-@@ -253,13 +254,13 @@
-     // Use 'select i8 true, %arg, undef' to simulate a 'no-op' instruction.
-     Value *TrueValue = ConstantInt::getTrue(F.getContext());
-     Value *UndefValue = UndefValue::get(Ty);
--    Instruction *SI = SelectInst::Create(TrueValue, AI, UndefValue,
-+    Instruction *SI = SelectInst::Create(TrueValue, &*AI, UndefValue,
-                                          AI->getName() + ".tmp",
--                                         AfterAllocaInsPt);
-+                                         &*AfterAllocaInsPt);
-     AI->replaceAllUsesWith(SI);
- 
-     // Reset the operand, because it  was clobbered by the RAUW above.
--    SI->setOperand(1, AI);
-+    SI->setOperand(1, &*AI);
-   }
- }
- 
-@@ -274,7 +275,7 @@
-       // Ignore obvious cases we don't have to handle. In particular, most
-       // instructions either have no uses or only have a single use inside the
-       // current block. Ignore them quickly.
--      Instruction *Inst = II;
-+      Instruction *Inst = &*II;
-       if (Inst->use_empty())
-         continue;
-       if (Inst->hasOneUse() &&
-@@ -355,7 +356,7 @@
-       DemotePHIToStack(PN);
- 
-     // Move the landingpad instruction back to the top of the landing pad block.
--    LPI->moveBefore(UnwindBlock->begin());
-+    LPI->moveBefore(&UnwindBlock->front());
-   }
- }
- 
-@@ -395,7 +396,7 @@
- 
-   Value *FuncCtx =
-       setupFunctionContext(F, makeArrayRef(LPads.begin(), LPads.end()));
--  BasicBlock *EntryBB = F.begin();
-+  BasicBlock *EntryBB = &F.front();
-   IRBuilder<> Builder(EntryBB->getTerminator());
- 
-   // Get a reference to the jump buffer.
-@@ -467,7 +468,7 @@
-         continue;
-       }
-       Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");
--      StackAddr->insertAfter(I);
-+      StackAddr->insertAfter(&*I);
-       Instruction *StoreStackAddr = new StoreInst(StackAddr, StackPtr, true);
-       StoreStackAddr->insertAfter(StackAddr);
-     }
---- lib/CodeGen/SlotIndexes.cpp	2014-04-21 19:02:50.000000000 -0700
-+++ lib/CodeGen/SlotIndexes.cpp	2015-12-07 07:32:28.357221215 -0800
-@@ -172,8 +172,8 @@
-   // optionally includes an additional position prior to MBB->begin(), indicated
-   // by the includeStart flag. This is done so that we can iterate MIs in a MBB
-   // in parallel with SlotIndexes, but there should be a better way to do this.
--  IndexList::iterator ListB = startIdx.listEntry();
--  IndexList::iterator ListI = endIdx.listEntry();
-+  IndexList::iterator ListB = startIdx.listEntry()->getIterator();
-+  IndexList::iterator ListI = endIdx.listEntry()->getIterator();
-   MachineBasicBlock::iterator MBBI = End;
-   bool pastStart = false;
-   while (ListI != ListB || MBBI != Begin || (includeStart && !pastStart)) {
---- lib/CodeGen/SpillPlacement.cpp	2014-10-02 15:23:14.000000000 -0700
-+++ lib/CodeGen/SpillPlacement.cpp	2015-12-07 07:33:14.076165375 -0800
-@@ -190,7 +190,7 @@
-   setThreshold(MBFI->getEntryFreq());
-   for (MachineFunction::iterator I = mf.begin(), E = mf.end(); I != E; ++I) {
-     unsigned Num = I->getNumber();
--    BlockFrequencies[Num] = MBFI->getBlockFreq(I);
-+    BlockFrequencies[Num] = MBFI->getBlockFreq(&*I);
-   }
- 
-   // We never change the function.
---- lib/CodeGen/SplitKit.cpp	2014-12-10 15:07:54.000000000 -0800
-+++ lib/CodeGen/SplitKit.cpp	2015-12-07 07:59:47.837252063 -0800
-@@ -176,10 +176,11 @@
-   UseE = UseSlots.end();
- 
-   // Loop over basic blocks where CurLI is live.
--  MachineFunction::iterator MFI = LIS.getMBBFromIndex(LVI->start);
-+  MachineFunction::iterator MFI =
-+    LIS.getMBBFromIndex(LVI->start)->getIterator();
-   for (;;) {
-     BlockInfo BI;
--    BI.MBB = MFI;
-+    BI.MBB = &*MFI;
-     SlotIndex Start, Stop;
-     std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB);
- 
-@@ -259,7 +260,7 @@
-     if (LVI->start < Stop)
-       ++MFI;
-     else
--      MFI = LIS.getMBBFromIndex(LVI->start);
-+      MFI = LIS.getMBBFromIndex(LVI->start)->getIterator();
-   }
- 
-   assert(getNumLiveBlocks() == countLiveBlocks(CurLI) && "Bad block count");
-@@ -275,8 +276,9 @@
-   unsigned Count = 0;
- 
-   // Loop over basic blocks where li is live.
--  MachineFunction::const_iterator MFI = LIS.getMBBFromIndex(LVI->start);
--  SlotIndex Stop = LIS.getMBBEndIdx(MFI);
-+  MachineFunction::const_iterator MFI =
-+    LIS.getMBBFromIndex(LVI->start)->getIterator();
-+  SlotIndex Stop = LIS.getMBBEndIdx(&*MFI);
-   for (;;) {
-     ++Count;
-     LVI = li->advanceTo(LVI, Stop);
-@@ -284,7 +286,7 @@
-       return Count;
-     do {
-       ++MFI;
--      Stop = LIS.getMBBEndIdx(MFI);
-+      Stop = LIS.getMBBEndIdx(&*MFI);
-     } while (Stop <= LVI->start);
-   }
- }
-@@ -866,9 +868,11 @@
-       // This value has multiple defs in RegIdx, but it wasn't rematerialized,
-       // so the live range is accurate. Add live-in blocks in [Start;End) to the
-       // LiveInBlocks.
--      MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start);
-+      MachineFunction::iterator MBB =
-+        LIS.getMBBFromIndex(Start)->getIterator();
-       SlotIndex BlockStart, BlockEnd;
--      std::tie(BlockStart, BlockEnd) = LIS.getSlotIndexes()->getMBBRange(MBB);
-+      std::tie(BlockStart, BlockEnd) =
-+        LIS.getSlotIndexes()->getMBBRange(&*MBB);
- 
-       // The first block may be live-in, or it may have its own def.
-       if (Start != BlockStart) {
-@@ -877,7 +881,7 @@
-         DEBUG(dbgs() << ':' << VNI->id << "*BB#" << MBB->getNumber());
-         // MBB has its own def. Is it also live-out?
-         if (BlockEnd <= End)
--          LRC.setLiveOutValue(MBB, VNI);
-+          LRC.setLiveOutValue(&*MBB, VNI);
- 
-         // Skip to the next block for live-in.
-         ++MBB;
-@@ -888,23 +892,23 @@
-       assert(Start <= BlockStart && "Expected live-in block");
-       while (BlockStart < End) {
-         DEBUG(dbgs() << ">BB#" << MBB->getNumber());
--        BlockEnd = LIS.getMBBEndIdx(MBB);
-+        BlockEnd = LIS.getMBBEndIdx(&*MBB);
-         if (BlockStart == ParentVNI->def) {
-           // This block has the def of a parent PHI, so it isn't live-in.
-           assert(ParentVNI->isPHIDef() && "Non-phi defined at block start?");
-           VNInfo *VNI = LR.extendInBlock(BlockStart, std::min(BlockEnd, End));
-           assert(VNI && "Missing def for complex mapped parent PHI");
-           if (End >= BlockEnd)
--            LRC.setLiveOutValue(MBB, VNI); // Live-out as well.
-+            LRC.setLiveOutValue(&*MBB, VNI); // Live-out as well.
-         } else {
-           // This block needs a live-in value.  The last block covered may not
-           // be live-out.
-           if (End < BlockEnd)
--            LRC.addLiveInBlock(LR, MDT[MBB], End);
-+            LRC.addLiveInBlock(LR, MDT[&*MBB], End);
-           else {
-             // Live-through, and we don't know the value.
--            LRC.addLiveInBlock(LR, MDT[MBB]);
--            LRC.setLiveOutValue(MBB, nullptr);
-+            LRC.addLiveInBlock(LR, MDT[&*MBB]);
-+            LRC.setLiveOutValue(&*MBB, nullptr);
-           }
-         }
-         BlockStart = BlockEnd;
---- lib/CodeGen/StackMapLivenessAnalysis.cpp	2015-01-13 09:47:59.000000000 -0800
-+++ lib/CodeGen/StackMapLivenessAnalysis.cpp	2015-12-07 08:03:47.966214485 -0800
-@@ -86,7 +86,7 @@
-        MBBI != MBBE; ++MBBI) {
-     DEBUG(dbgs() << "****** BB " << MBBI->getName() << " ******\n");
-     LiveRegs.init(TRI);
--    LiveRegs.addLiveOuts(MBBI);
-+    LiveRegs.addLiveOuts(&*MBBI);
-     bool HasStackMap = false;
-     // Reverse iterate over all instructions and add the current live register
-     // set to an instruction if we encounter a patchpoint instruction.
---- lib/CodeGen/StackProtector.cpp	2014-12-21 13:52:38.000000000 -0800
-+++ lib/CodeGen/StackProtector.cpp	2015-12-07 08:06:06.725425403 -0800
-@@ -377,7 +377,8 @@
-   Value *StackGuardVar = nullptr; // The stack guard variable.
- 
-   for (Function::iterator I = F->begin(), E = F->end(); I != E;) {
--    BasicBlock *BB = I++;
-+    BasicBlock *BB = &*I;
-+    ++I;
-     ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
-     if (!RI)
-       continue;
-@@ -437,7 +438,7 @@
-       BasicBlock *FailBB = CreateFailBB();
- 
-       // Split the basic block before the return instruction.
--      BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return");
-+      BasicBlock *NewBB = BB->splitBasicBlock(RI->getIterator(), "SP_return");
- 
-       // Update the dominator tree if we need to.
-       if (DT && DT->isReachableFromEntry(BB)) {
---- lib/CodeGen/TailDuplication.cpp	2014-08-04 19:39:49.000000000 -0700
-+++ lib/CodeGen/TailDuplication.cpp	2015-12-07 08:11:12.192736388 -0800
-@@ -161,7 +161,7 @@
- 
- static void VerifyPHIs(MachineFunction &MF, bool CheckExtra) {
-   for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ++I) {
--    MachineBasicBlock *MBB = I;
-+    MachineBasicBlock *MBB = &*I;
-     SmallSetVector<MachineBasicBlock*, 8> Preds(MBB->pred_begin(),
-                                                 MBB->pred_end());
-     MachineBasicBlock::iterator MI = MBB->begin();
-@@ -322,7 +322,8 @@
-   }
- 
-   for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
--    MachineBasicBlock *MBB = I++;
-+    MachineBasicBlock *MBB = &*I;
-+    ++I;
- 
-     if (NumTails == TailDupLimit)
-       break;
-@@ -697,7 +698,7 @@
-                  << "From simple Succ: " << *TailBB);
- 
-     MachineBasicBlock *NewTarget = *TailBB->succ_begin();
--    MachineBasicBlock *NextBB = std::next(MachineFunction::iterator(PredBB));
-+    MachineBasicBlock *NextBB = &*std::next(PredBB->getIterator());
- 
-     // Make PredFBB explicit.
-     if (PredCond.empty())
-@@ -855,7 +856,7 @@
-   // If TailBB was duplicated into all its predecessors except for the prior
-   // block, which falls through unconditionally, move the contents of this
-   // block into the prior block.
--  MachineBasicBlock *PrevBB = std::prev(MachineFunction::iterator(TailBB));
-+  MachineBasicBlock *PrevBB = &*std::prev(TailBB->getIterator());
-   MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
-   SmallVector<MachineOperand, 4> PriorCond;
-   // This has to check PrevBB->succ_size() because EH edges are ignored by
---- lib/CodeGen/TwoAddressInstructionPass.cpp	2014-11-18 23:49:26.000000000 -0800
-+++ lib/CodeGen/TwoAddressInstructionPass.cpp	2015-12-07 08:24:37.706267592 -0800
-@@ -634,7 +634,7 @@
-                                               unsigned RegA, unsigned RegB,
-                                               unsigned Dist) {
-   // FIXME: Why does convertToThreeAddress() need an iterator reference?
--  MachineFunction::iterator MFI = MBB;
-+  MachineFunction::iterator MFI = MBB->getIterator();
-   MachineInstr *NewMI = TII->convertToThreeAddress(MFI, mi, LV);
-   assert(MBB == MFI && "convertToThreeAddress changed iterator reference");
-   if (!NewMI)
-@@ -1535,7 +1535,7 @@
-   TiedOperandMap TiedOperands;
-   for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
-        MBBI != MBBE; ++MBBI) {
--    MBB = MBBI;
-+    MBB = &*MBBI;
-     unsigned Dist = 0;
-     DistanceMap.clear();
-     SrcRegMap.clear();
---- lib/CodeGen/UnreachableBlockElim.cpp	2014-08-24 16:23:06.000000000 -0700
-+++ lib/CodeGen/UnreachableBlockElim.cpp	2015-12-07 08:28:10.169471890 -0800
-@@ -71,8 +71,8 @@
-   // in them.
-   std::vector<BasicBlock*> DeadBlocks;
-   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
--    if (!Reachable.count(I)) {
--      BasicBlock *BB = I;
-+    if (!Reachable.count(&*I)) {
-+      BasicBlock *BB = &*I;
-       DeadBlocks.push_back(BB);
-       while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
-         PN->replaceAllUsesWith(Constant::getNullValue(PN->getType()));
-@@ -131,7 +131,7 @@
-   // in them.
-   std::vector<MachineBasicBlock*> DeadBlocks;
-   for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) {
--    MachineBasicBlock *BB = I;
-+    MachineBasicBlock *BB = &*I;
- 
-     // Test for deadness.
-     if (!Reachable.count(BB)) {
-@@ -167,7 +167,7 @@
- 
-   // Cleanup PHI nodes.
-   for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) {
--    MachineBasicBlock *BB = I;
-+    MachineBasicBlock *BB = &*I;
-     // Prune unneeded PHI entries.
-     SmallPtrSet<MachineBasicBlock*, 8> preds(BB->pred_begin(),
-                                              BB->pred_end());
---- lib/CodeGen/VirtRegMap.cpp	2014-12-10 16:59:06.000000000 -0800
-+++ lib/CodeGen/VirtRegMap.cpp	2015-12-07 08:29:40.895828212 -0800
-@@ -312,7 +312,7 @@
-     bool IsExitBB = MBBI->succ_empty();
-     for (MachineBasicBlock::instr_iterator
-            MII = MBBI->instr_begin(), MIE = MBBI->instr_end(); MII != MIE;) {
--      MachineInstr *MI = MII;
-+      MachineInstr *MI = &*MII;
-       ++MII;
- 
-       // Check if this instruction is a call to a noreturn function.  If this
---- lib/ExecutionEngine/ExecutionEngine.cpp	2014-12-02 16:51:19.000000000 -0800
-+++ lib/ExecutionEngine/ExecutionEngine.cpp	2015-12-07 12:04:19.264547988 -0800
-@@ -190,10 +190,10 @@
-   MutexGuard locked(lock);
- 
-   for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
--    EEState.RemoveMapping(FI);
-+    EEState.RemoveMapping(&*FI);
-   for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
-        GI != GE; ++GI)
--    EEState.RemoveMapping(GI);
-+    EEState.RemoveMapping(&*GI);
- }
- 
- void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
---- lib/ExecutionEngine/Interpreter/Execution.cpp	2014-04-27 21:05:08.000000000 -0700
-+++ lib/ExecutionEngine/Interpreter/Execution.cpp	2015-12-07 12:10:37.392666513 -0800
-@@ -2091,7 +2091,7 @@
-   }
- 
-   // Get pointers to first LLVM BB & Instruction in function.
--  StackFrame.CurBB     = F->begin();
-+  StackFrame.CurBB     = &F->front();
-   StackFrame.CurInst   = StackFrame.CurBB->begin();
- 
-   // Run through the function arguments and initialize their values...
-@@ -2103,7 +2103,7 @@
-   unsigned i = 0;
-   for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); 
-        AI != E; ++AI, ++i)
--    SetValue(AI, ArgVals[i], StackFrame);
-+    SetValue(&*AI, ArgVals[i], StackFrame);
- 
-   // Handle varargs arguments...
-   StackFrame.VarArgs.assign(ArgVals.begin()+i, ArgVals.end());
---- lib/IR/AsmWriter.cpp	2015-01-14 19:59:43.000000000 -0800
-+++ lib/IR/AsmWriter.cpp	2015-11-24 08:43:48.354963500 -0800
-@@ -674,14 +674,14 @@
-   for (Module::const_global_iterator I = TheModule->global_begin(),
-          E = TheModule->global_end(); I != E; ++I) {
-     if (!I->hasName())
--      CreateModuleSlot(I);
-+      CreateModuleSlot(&(*I));
-   }
- 
-   // Add metadata used by named metadata.
-   for (Module::const_named_metadata_iterator
-          I = TheModule->named_metadata_begin(),
-          E = TheModule->named_metadata_end(); I != E; ++I) {
--    const NamedMDNode *NMD = I;
-+    const NamedMDNode *NMD = &(*I);
-     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
-       CreateMetadataSlot(NMD->getOperand(i));
-   }
-@@ -690,7 +690,7 @@
-        I != E; ++I) {
-     if (!I->hasName())
-       // Add all the unnamed functions to the table.
--      CreateModuleSlot(I);
-+      CreateModuleSlot(&(*I));
- 
-     // Add all the function attributes to the table.
-     // FIXME: Add attributes of other objects?
-@@ -711,7 +711,7 @@
-   for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
-       AE = TheFunction->arg_end(); AI != AE; ++AI)
-     if (!AI->hasName())
--      CreateFunctionSlot(AI);
-+      CreateFunctionSlot(&(*AI));
- 
-   ST_DEBUG("Inserting Instructions:\n");
- 
-@@ -721,12 +721,12 @@
-   for (Function::const_iterator BB = TheFunction->begin(),
-        E = TheFunction->end(); BB != E; ++BB) {
-     if (!BB->hasName())
--      CreateFunctionSlot(BB);
-+      CreateFunctionSlot(&(*BB));
- 
-     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E;
-          ++I) {
-       if (!I->getType()->isVoidTy() && !I->hasName())
--        CreateFunctionSlot(I);
-+        CreateFunctionSlot(&(*I));
- 
-       // Intrinsics can directly use metadata.  We allow direct calls to any
-       // llvm.foo function here, because the target may not be linked into the
-@@ -1607,21 +1607,22 @@
-   if (!M->global_empty()) Out << '\n';
-   for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
-        I != E; ++I) {
--    printGlobal(I); Out << '\n';
-+    printGlobal(&(*I));
-+    Out << '\n';
-   }
- 
-   // Output all aliases.
-   if (!M->alias_empty()) Out << "\n";
-   for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
-        I != E; ++I)
--    printAlias(I);
-+    printAlias(&(*I));
- 
-   // Output global use-lists.
-   printUseLists(nullptr);
- 
-   // Output all of the functions.
-   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
--    printFunction(I);
-+    printFunction(&(*I));
-   assert(UseListOrders.empty() && "All use-lists should have been consumed");
- 
-   // Output all attribute groups.
-@@ -1635,7 +1636,7 @@
- 
-   for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
-        E = M->named_metadata_end(); I != E; ++I)
--    printNamedMDNode(I);
-+    printNamedMDNode(&(*I));
- 
-   // Output metadata.
-   if (!Machine.mdn_empty()) {
-@@ -1936,7 +1937,7 @@
-          I != E; ++I) {
-       // Insert commas as we go... the first arg doesn't get a comma
-       if (I != F->arg_begin()) Out << ", ";
--      printArgument(I, Attrs, Idx);
-+      printArgument(&(*I), Attrs, Idx);
-       Idx++;
-     }
-   } else {
-@@ -1988,7 +1989,7 @@
-     Out << " {";
-     // Output all of the function's basic blocks.
-     for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
--      printBasicBlock(I);
-+      printBasicBlock(&(*I));
- 
-     // Output the function's use-lists.
-     printUseLists(F);
---- lib/IR/AutoUpgrade.cpp	2015-01-14 03:23:27.000000000 -0800
-+++ lib/IR/AutoUpgrade.cpp	2015-11-24 09:08:05.216149050 -0800
-@@ -278,7 +278,7 @@
-   Function *F = CI->getCalledFunction();
-   LLVMContext &C = CI->getContext();
-   IRBuilder<> Builder(C);
--  Builder.SetInsertPoint(CI->getParent(), CI);
-+  Builder.SetInsertPoint(CI->getParent(), CI->getIterator());
- 
-   assert(F && "Intrinsic call is not direct?");
- 
-@@ -304,7 +304,7 @@
-                Name == "llvm.x86.avx.movnt.ps.256" ||
-                Name == "llvm.x86.avx.movnt.pd.256") {
-       IRBuilder<> Builder(C);
--      Builder.SetInsertPoint(CI->getParent(), CI);
-+      Builder.SetInsertPoint(CI->getParent(), CI->getIterator());
- 
-       Module *M = F->getParent();
-       SmallVector<Metadata *, 1> Elts;
---- lib/IR/BasicBlock.cpp	2014-12-22 05:00:36.000000000 -0800
-+++ lib/IR/BasicBlock.cpp	2015-11-24 09:18:34.413275013 -0800
-@@ -60,7 +60,7 @@
-   assert(!Parent && "Already has a parent");
- 
-   if (InsertBefore)
--    NewParent->getBasicBlockList().insert(InsertBefore, this);
-+    NewParent->getBasicBlockList().insert(InsertBefore->getIterator(), this);
-   else
-     NewParent->getBasicBlockList().push_back(this);
- }
-@@ -95,26 +95,28 @@
- }
- 
- void BasicBlock::removeFromParent() {
--  getParent()->getBasicBlockList().remove(this);
-+  getParent()->getBasicBlockList().remove(getIterator());
- }
- 
- void BasicBlock::eraseFromParent() {
--  getParent()->getBasicBlockList().erase(this);
-+  getParent()->getBasicBlockList().erase(getIterator());
- }
- 
- /// moveBefore - Unlink this basic block from its current function and
- /// insert it into the function that MovePos lives in, right before MovePos.
- void BasicBlock::moveBefore(BasicBlock *MovePos) {
--  MovePos->getParent()->getBasicBlockList().splice(MovePos,
--                       getParent()->getBasicBlockList(), this);
-+  MovePos->getParent()->getBasicBlockList().splice(MovePos->getIterator(),
-+                       getParent()->getBasicBlockList(), getIterator());
- }
- 
- /// moveAfter - Unlink this basic block from its current function and
- /// insert it into the function that MovePos lives in, right after MovePos.
- void BasicBlock::moveAfter(BasicBlock *MovePos) {
--  Function::iterator I = MovePos;
--  MovePos->getParent()->getBasicBlockList().splice(++I,
--                                       getParent()->getBasicBlockList(), this);
-+  Function::iterator I = MovePos->getIterator();
-+  Function::iterator II = ++I;
-+  MovePos->getParent()->getBasicBlockList().splice(II,
-+                                       getParent()->getBasicBlockList(),
-+                                       getIterator());
- }
- 
- 
-@@ -200,7 +202,7 @@
- }
- 
- BasicBlock::iterator BasicBlock::getFirstInsertionPt() {
--  iterator InsertPt = getFirstNonPHI();
-+  iterator InsertPt = getFirstNonPHI()->getIterator();
-   if (isa<LandingPadInst>(InsertPt)) ++InsertPt;
-   return InsertPt;
- }
---- lib/IR/Core.cpp	2015-01-29 09:33:19.000000000 -0800
-+++ lib/IR/Core.cpp	2015-11-24 20:09:32.108977930 -0800
-@@ -1517,7 +1517,8 @@
-   Module::global_iterator I = Mod->global_begin();
-   if (I == Mod->global_end())
-     return nullptr;
--  return wrap(I);
-+
-+  return wrap(&(*I));
- }
- 
- LLVMValueRef LLVMGetLastGlobal(LLVMModuleRef M) {
-@@ -1525,23 +1526,28 @@
-   Module::global_iterator I = Mod->global_end();
-   if (I == Mod->global_begin())
-     return nullptr;
--  return wrap(--I);
-+
-+  --I;
-+  return wrap(&(*I));
- }
- 
- LLVMValueRef LLVMGetNextGlobal(LLVMValueRef GlobalVar) {
-   GlobalVariable *GV = unwrap<GlobalVariable>(GlobalVar);
--  Module::global_iterator I = GV;
-+  Module::global_iterator I(GV);
-   if (++I == GV->getParent()->global_end())
-     return nullptr;
--  return wrap(I);
-+
-+  return wrap(&(*I));
- }
- 
- LLVMValueRef LLVMGetPreviousGlobal(LLVMValueRef GlobalVar) {
-   GlobalVariable *GV = unwrap<GlobalVariable>(GlobalVar);
--  Module::global_iterator I = GV;
-+  Module::global_iterator I(GV);
-   if (I == GV->getParent()->global_begin())
-     return nullptr;
--  return wrap(--I);
-+
-+  --I;
-+  return wrap(&(*I));
- }
- 
- void LLVMDeleteGlobal(LLVMValueRef GlobalVar) {
-@@ -1550,8 +1556,9 @@
- 
- LLVMValueRef LLVMGetInitializer(LLVMValueRef GlobalVar) {
-   GlobalVariable* GV = unwrap<GlobalVariable>(GlobalVar);
--  if ( !GV->hasInitializer() )
-+  if (!GV->hasInitializer())
-     return nullptr;
-+
-   return wrap(GV->getInitializer());
- }
- 
-@@ -1650,7 +1657,8 @@
-   Module::iterator I = Mod->begin();
-   if (I == Mod->end())
-     return nullptr;
--  return wrap(I);
-+
-+  return wrap(&(*I));
- }
- 
- LLVMValueRef LLVMGetLastFunction(LLVMModuleRef M) {
-@@ -1658,23 +1666,28 @@
-   Module::iterator I = Mod->end();
-   if (I == Mod->begin())
-     return nullptr;
--  return wrap(--I);
-+
-+  --I;
-+  return wrap(&(*I));
- }
- 
- LLVMValueRef LLVMGetNextFunction(LLVMValueRef Fn) {
-   Function *Func = unwrap<Function>(Fn);
--  Module::iterator I = Func;
-+  Module::iterator I(Func);
-   if (++I == Func->getParent()->end())
-     return nullptr;
--  return wrap(I);
-+
-+  return wrap(&(*I));
- }
- 
- LLVMValueRef LLVMGetPreviousFunction(LLVMValueRef Fn) {
-   Function *Func = unwrap<Function>(Fn);
--  Module::iterator I = Func;
-+  Module::iterator I(Func);
-   if (I == Func->getParent()->begin())
-     return nullptr;
--  return wrap(--I);
-+
-+  --I;
-+  return wrap(&(*I));
- }
- 
- void LLVMDeleteFunction(LLVMValueRef Fn) {
-@@ -1684,6 +1697,7 @@
- unsigned LLVMGetIntrinsicID(LLVMValueRef Fn) {
-   if (Function *F = dyn_cast<Function>(unwrap(Fn)))
-     return F->getIntrinsicID();
-+
-   return 0;
- }
- 
-@@ -1698,7 +1712,7 @@
- 
- const char *LLVMGetGC(LLVMValueRef Fn) {
-   Function *F = unwrap<Function>(Fn);
--  return F->hasGC()? F->getGC() : nullptr;
-+  return F->hasGC() ? F->getGC() : nullptr;
- }
- 
- void LLVMSetGC(LLVMValueRef Fn, const char *GC) {
-@@ -1761,14 +1775,15 @@
-   Function *Fn = unwrap<Function>(FnRef);
-   for (Function::arg_iterator I = Fn->arg_begin(),
-                               E = Fn->arg_end(); I != E; I++)
--    *ParamRefs++ = wrap(I);
-+    *ParamRefs++ = wrap(&(*I));
- }
- 
- LLVMValueRef LLVMGetParam(LLVMValueRef FnRef, unsigned index) {
-   Function::arg_iterator AI = unwrap<Function>(FnRef)->arg_begin();
-   while (index --> 0)
-     AI++;
--  return wrap(AI);
-+
-+  return wrap(&(*AI));
- }
- 
- LLVMValueRef LLVMGetParamParent(LLVMValueRef V) {
-@@ -1780,7 +1795,8 @@
-   Function::arg_iterator I = Func->arg_begin();
-   if (I == Func->arg_end())
-     return nullptr;
--  return wrap(I);
-+
-+  return wrap(&(*I));
- }
- 
- LLVMValueRef LLVMGetLastParam(LLVMValueRef Fn) {
-@@ -1788,23 +1804,28 @@
-   Function::arg_iterator I = Func->arg_end();
-   if (I == Func->arg_begin())
-     return nullptr;
--  return wrap(--I);
-+
-+  --I;
-+  return wrap(&(*I));
- }
- 
- LLVMValueRef LLVMGetNextParam(LLVMValueRef Arg) {
-   Argument *A = unwrap<Argument>(Arg);
--  Function::arg_iterator I = A;
-+  Function::arg_iterator I(A);
-   if (++I == A->getParent()->arg_end())
-     return nullptr;
--  return wrap(I);
-+
-+  return wrap(&(*I));
- }
- 
- LLVMValueRef LLVMGetPreviousParam(LLVMValueRef Arg) {
-   Argument *A = unwrap<Argument>(Arg);
--  Function::arg_iterator I = A;
-+  Function::arg_iterator I(A);
-   if (I == A->getParent()->arg_begin())
-     return nullptr;
--  return wrap(--I);
-+
-+  --I;
-+  return wrap(&(*I));
- }
- 
- void LLVMAddAttribute(LLVMValueRef Arg, LLVMAttribute PA) {
-@@ -1862,7 +1883,7 @@
- void LLVMGetBasicBlocks(LLVMValueRef FnRef, LLVMBasicBlockRef *BasicBlocksRefs){
-   Function *Fn = unwrap<Function>(FnRef);
-   for (Function::iterator I = Fn->begin(), E = Fn->end(); I != E; I++)
--    *BasicBlocksRefs++ = wrap(I);
-+    *BasicBlocksRefs++ = wrap(&(*I));
- }
- 
- LLVMBasicBlockRef LLVMGetEntryBasicBlock(LLVMValueRef Fn) {
-@@ -1874,7 +1895,8 @@
-   Function::iterator I = Func->begin();
-   if (I == Func->end())
-     return nullptr;
--  return wrap(I);
-+
-+  return wrap(&(*I));
- }
- 
- LLVMBasicBlockRef LLVMGetLastBasicBlock(LLVMValueRef Fn) {
-@@ -1882,23 +1904,28 @@
-   Function::iterator I = Func->end();
-   if (I == Func->begin())
-     return nullptr;
--  return wrap(--I);
-+
-+  --I;
-+  return wrap(&(*I));
- }
- 
- LLVMBasicBlockRef LLVMGetNextBasicBlock(LLVMBasicBlockRef BB) {
-   BasicBlock *Block = unwrap(BB);
--  Function::iterator I = Block;
-+  Function::iterator I(Block);
-   if (++I == Block->getParent()->end())
-     return nullptr;
--  return wrap(I);
-+
-+  return wrap(&(*I));
- }
- 
- LLVMBasicBlockRef LLVMGetPreviousBasicBlock(LLVMBasicBlockRef BB) {
-   BasicBlock *Block = unwrap(BB);
--  Function::iterator I = Block;
-+  Function::iterator I(Block);
-   if (I == Block->getParent()->begin())
-     return nullptr;
--  return wrap(--I);
-+
-+  --I;
-+  return wrap(&(*I));
- }
- 
- LLVMBasicBlockRef LLVMAppendBasicBlockInContext(LLVMContextRef C,
-@@ -1950,7 +1977,8 @@
-   BasicBlock::iterator I = Block->begin();
-   if (I == Block->end())
-     return nullptr;
--  return wrap(I);
-+
-+  return wrap(&(*I));
- }
- 
- LLVMValueRef LLVMGetLastInstruction(LLVMBasicBlockRef BB) {
-@@ -1958,23 +1986,28 @@
-   BasicBlock::iterator I = Block->end();
-   if (I == Block->begin())
-     return nullptr;
--  return wrap(--I);
-+
-+  --I;
-+  return wrap(&(*I));
- }
- 
- LLVMValueRef LLVMGetNextInstruction(LLVMValueRef Inst) {
-   Instruction *Instr = unwrap<Instruction>(Inst);
--  BasicBlock::iterator I = Instr;
-+  BasicBlock::iterator I(Instr);
-   if (++I == Instr->getParent()->end())
-     return nullptr;
--  return wrap(I);
-+
-+  return wrap(&(*I));
- }
- 
- LLVMValueRef LLVMGetPreviousInstruction(LLVMValueRef Inst) {
-   Instruction *Instr = unwrap<Instruction>(Inst);
--  BasicBlock::iterator I = Instr;
-+  BasicBlock::iterator I(Instr);
-   if (I == Instr->getParent()->begin())
-     return nullptr;
--  return wrap(--I);
-+
-+  --I;
-+  return wrap(&(*I));
- }
- 
- void LLVMInstructionEraseFromParent(LLVMValueRef Inst) {
-@@ -2142,12 +2175,12 @@
-                          LLVMValueRef Instr) {
-   BasicBlock *BB = unwrap(Block);
-   Instruction *I = Instr? unwrap<Instruction>(Instr) : (Instruction*) BB->end();
--  unwrap(Builder)->SetInsertPoint(BB, I);
-+  unwrap(Builder)->SetInsertPoint(BB, I->getIterator());
- }
- 
- void LLVMPositionBuilderBefore(LLVMBuilderRef Builder, LLVMValueRef Instr) {
-   Instruction *I = unwrap<Instruction>(Instr);
--  unwrap(Builder)->SetInsertPoint(I->getParent(), I);
-+  unwrap(Builder)->SetInsertPoint(I->getParent(), I->getIterator());
- }
- 
- void LLVMPositionBuilderAtEnd(LLVMBuilderRef Builder, LLVMBasicBlockRef Block) {
---- lib/IR/DebugInfo.cpp	2015-02-12 15:46:59.000000000 -0800
-+++ lib/IR/DebugInfo.cpp	2015-11-24 20:11:47.916206795 -0800
-@@ -1485,7 +1485,7 @@
- 
-   for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
-          NME = M.named_metadata_end(); NMI != NME;) {
--    NamedMDNode *NMD = NMI;
-+    NamedMDNode *NMD = &(*NMI);
-     ++NMI;
-     if (NMD->getName().startswith("llvm.dbg.")) {
-       NMD->eraseFromParent();
---- lib/IR/Function.cpp	2014-12-24 23:49:20.000000000 -0800
-+++ lib/IR/Function.cpp	2015-11-27 09:29:07.971979862 -0800
-@@ -228,11 +228,11 @@
- }
- 
- void Function::removeFromParent() {
--  getParent()->getFunctionList().remove(this);
-+  getParent()->getFunctionList().remove(getIterator());
- }
- 
- void Function::eraseFromParent() {
--  getParent()->getFunctionList().erase(this);
-+  getParent()->getFunctionList().erase(getIterator());
- }
- 
- //===----------------------------------------------------------------------===//
---- lib/IR/Globals.cpp	2014-12-22 05:00:36.000000000 -0800
-+++ lib/IR/Globals.cpp	2015-11-27 06:06:12.109691445 -0800
-@@ -178,7 +178,7 @@
-   }
- 
-   if (Before)
--    Before->getParent()->getGlobalList().insert(Before, this);
-+    Before->getParent()->getGlobalList().insert(Before->getIterator(), this);
-   else
-     M.getGlobalList().push_back(this);
- }
-@@ -188,11 +188,11 @@
- }
- 
- void GlobalVariable::removeFromParent() {
--  getParent()->getGlobalList().remove(this);
-+  getParent()->getGlobalList().remove(getIterator());
- }
- 
- void GlobalVariable::eraseFromParent() {
--  getParent()->getGlobalList().erase(this);
-+  getParent()->getGlobalList().erase(getIterator());
- }
- 
- void GlobalVariable::replaceUsesOfWithOnConstant(Value *From, Value *To,
-@@ -290,11 +290,11 @@
- }
- 
- void GlobalAlias::removeFromParent() {
--  getParent()->getAliasList().remove(this);
-+  getParent()->getAliasList().remove(getIterator());
- }
- 
- void GlobalAlias::eraseFromParent() {
--  getParent()->getAliasList().erase(this);
-+  getParent()->getAliasList().erase(getIterator());
- }
- 
- void GlobalAlias::setAliasee(Constant *Aliasee) {
---- lib/IR/Instruction.cpp	2014-12-22 05:00:36.000000000 -0800
-+++ lib/IR/Instruction.cpp	2015-11-27 07:26:46.480147123 -0800
-@@ -26,9 +26,9 @@
- 
-   // If requested, insert this instruction into a basic block...
-   if (InsertBefore) {
--    assert(InsertBefore->getParent() &&
--           "Instruction to insert before is not in a basic block!");
--    InsertBefore->getParent()->getInstList().insert(InsertBefore, this);
-+    BasicBlock *BB = InsertBefore->getParent();
-+    assert(BB && "Instruction to insert before is not in a basic block!");
-+    BB->getInstList().insert(InsertBefore->getIterator(), this);
-   }
- }
- 
-@@ -59,31 +59,33 @@
- }
- 
- void Instruction::removeFromParent() {
--  getParent()->getInstList().remove(this);
-+  getParent()->getInstList().remove(getIterator());
- }
- 
- void Instruction::eraseFromParent() {
--  getParent()->getInstList().erase(this);
-+  getParent()->getInstList().erase(getIterator());
- }
- 
- /// insertBefore - Insert an unlinked instructions into a basic block
- /// immediately before the specified instruction.
- void Instruction::insertBefore(Instruction *InsertPos) {
--  InsertPos->getParent()->getInstList().insert(InsertPos, this);
-+  InsertPos->getParent()->getInstList().insert(InsertPos->getIterator(), this);
- }
- 
- /// insertAfter - Insert an unlinked instructions into a basic block
- /// immediately after the specified instruction.
- void Instruction::insertAfter(Instruction *InsertPos) {
--  InsertPos->getParent()->getInstList().insertAfter(InsertPos, this);
-+  InsertPos->getParent()->getInstList().insertAfter(InsertPos->getIterator(),
-+                                                    this);
- }
- 
- /// moveBefore - Unlink this instruction from its current basic block and
- /// insert it into the basic block that MovePos lives in, right before
- /// MovePos.
- void Instruction::moveBefore(Instruction *MovePos) {
--  MovePos->getParent()->getInstList().splice(MovePos,getParent()->getInstList(),
--                                             this);
-+  MovePos->getParent()->getInstList().splice(MovePos->getIterator(),
-+                                             getParent()->getInstList(),
-+                                             getIterator());
- }
- 
- /// Set or clear the unsafe-algebra flag on this instruction, which must be an
---- lib/IR/Module.cpp	2014-12-22 05:00:36.000000000 -0800
-+++ lib/IR/Module.cpp	2015-11-27 09:30:00.064132788 -0800
-@@ -274,7 +274,7 @@
- /// delete it.
- void Module::eraseNamedMetadata(NamedMDNode *NMD) {
-   static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
--  NamedMDList.erase(NMD);
-+  NamedMDList.erase(NMD->getIterator());
- }
- 
- bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) {
---- lib/IR/SymbolTableListTraitsImpl.h	2014-08-13 09:26:38.000000000 -0700
-+++ lib/IR/SymbolTableListTraitsImpl.h	2015-11-24 12:37:36.693556920 -0800
-@@ -57,7 +57,7 @@
-     for (typename iplist<ValueSubClass>::iterator I = ItemList.begin();
-          I != ItemList.end(); ++I)
-       if (I->hasName())
--        NewST->reinsertValue(I);
-+        NewST->reinsertValue(&(*I));
-   }
-   
- }
---- lib/IR/TypeFinder.cpp	2014-12-09 10:38:53.000000000 -0800
-+++ lib/IR/TypeFinder.cpp	2015-11-27 07:40:03.669762910 -0800
-@@ -53,7 +53,7 @@
-     // First incorporate the arguments.
-     for (Function::const_arg_iterator AI = FI->arg_begin(),
-            AE = FI->arg_end(); AI != AE; ++AI)
--      incorporateValue(AI);
-+      incorporateValue(&(*AI));
- 
-     for (Function::const_iterator BB = FI->begin(), E = FI->end();
-          BB != E;++BB)
-@@ -82,7 +82,7 @@
- 
-   for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
-          E = M.named_metadata_end(); I != E; ++I) {
--    const NamedMDNode *NMD = I;
-+    const NamedMDNode *NMD = &(*I);
-     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
-       incorporateMDNode(NMD->getOperand(i));
-   }
---- lib/IR/Verifier.cpp	2015-01-12 19:46:47.000000000 -0800
-+++ lib/IR/Verifier.cpp	2015-11-27 09:27:19.724275928 -0800
-@@ -81,7 +81,8 @@
- static cl::opt<bool> VerifyDebugInfo("verify-debug-info", cl::init(false));
- 
- namespace {
--struct VerifierSupport {
-+class VerifierSupport {
-+public:
-   raw_ostream &OS;
-   const Module *M;
- 
-@@ -89,11 +90,15 @@
-   bool Broken;
- 
-   explicit VerifierSupport(raw_ostream &OS)
--      : OS(OS), M(nullptr), Broken(false) {}
-+    : OS(OS), M(nullptr), Broken(false) { }
-+
-+  ~VerifierSupport() { }
- 
--  void WriteValue(const Value *V) {
-+private:
-+  void Write(const Value *V) {
-     if (!V)
-       return;
-+
-     if (isa<Instruction>(V)) {
-       OS << *V << '\n';
-     } else {
-@@ -102,81 +107,69 @@
-     }
-   }
- 
--  void WriteMetadata(const Metadata *MD) {
-+  void Write(const Metadata *MD) {
-     if (!MD)
-       return;
-+
-     MD->printAsOperand(OS, true, M);
-     OS << '\n';
-   }
- 
--  void WriteType(Type *T) {
-+  void Write(Type *T) {
-     if (!T)
-       return;
-+
-     OS << ' ' << *T;
-   }
- 
--  void WriteComdat(const Comdat *C) {
-+  void Write(const Comdat *C) {
-     if (!C)
-       return;
-+
-     OS << *C;
-   }
- 
--  // CheckFailed - A check failed, so print out the condition and the message
--  // that failed.  This provides a nice place to put a breakpoint if you want
--  // to see why something is not correct.
--  void CheckFailed(const Twine &Message, const Value *V1 = nullptr,
--                   const Value *V2 = nullptr, const Value *V3 = nullptr,
--                   const Value *V4 = nullptr) {
--    OS << Message.str() << "\n";
--    WriteValue(V1);
--    WriteValue(V2);
--    WriteValue(V3);
--    WriteValue(V4);
--    Broken = true;
--  }
-+  void Write(const NamedMDNode *NMD) {
-+    if (!NMD)
-+      return;
- 
--  void CheckFailed(const Twine &Message, const Metadata *V1, const Metadata *V2,
--                   const Metadata *V3 = nullptr, const Metadata *V4 = nullptr) {
--    OS << Message.str() << "\n";
--    WriteMetadata(V1);
--    WriteMetadata(V2);
--    WriteMetadata(V3);
--    WriteMetadata(V4);
--    Broken = true;
-+    NMD->print(OS);
-+    OS << "\n";
-   }
- 
--  void CheckFailed(const Twine &Message, const Metadata *V1,
--                   const Value *V2 = nullptr) {
--    OS << Message.str() << "\n";
--    WriteMetadata(V1);
--    WriteValue(V2);
--    Broken = true;
-+  template<class T>
-+  void Write(const MDTupleTypedArrayWrapper<T> &MD) {
-+    Write(MD.get());
-   }
- 
--  void CheckFailed(const Twine &Message, const Value *V1, Type *T2,
--                   const Value *V3 = nullptr) {
--    OS << Message.str() << "\n";
--    WriteValue(V1);
--    WriteType(T2);
--    WriteValue(V3);
--    Broken = true;
-+  template<class NodeTy> void Write(const ilist_iterator<NodeTy> &I) {
-+    Write(&(*I));
-   }
- 
--  void CheckFailed(const Twine &Message, Type *T1, Type *T2 = nullptr,
--                   Type *T3 = nullptr) {
--    OS << Message.str() << "\n";
--    WriteType(T1);
--    WriteType(T2);
--    WriteType(T3);
-+  template <typename T1, typename... Ts>
-+    void WriteTs(const T1 &V1, const Ts &... Vs) {
-+      Write(V1);
-+      WriteTs(Vs...);
-+    }
-+
-+  template <typename... Ts> void WriteTs() {}
-+
-+public:
-+  // CheckFailed - A check failed, so print out the condition and the message
-+  // that failed.  This provides a nice place to put a breakpoint if you want
-+  // to see why something is not correct.
-+  void CheckFailed(const Twine &Message) {
-+    OS << Message << '\n';
-     Broken = true;
-   }
- 
--  void CheckFailed(const Twine &Message, const Comdat *C) {
--    OS << Message.str() << "\n";
--    WriteComdat(C);
--    Broken = true;
-+  template <typename T1, typename... Ts>
-+  void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) {
-+    CheckFailed(Message);
-+    WriteTs(V1, Vs...);
-   }
- };
-+
- class Verifier : public InstVisitor<Verifier>, VerifierSupport {
-   friend class InstVisitor<Verifier>;
- 
-@@ -204,8 +197,10 @@
- 
- public:
-   explicit Verifier(raw_ostream &OS = dbgs())
--      : VerifierSupport(OS), Context(nullptr), PersonalityFn(nullptr),
--        SawFrameAllocate(false) {}
-+    : InstVisitor<Verifier>(),
-+    VerifierSupport(OS), Context(nullptr), DT(),
-+    InstsInThisBlock(), MDNodes(),
-+    PersonalityFn(nullptr), SawFrameAllocate(false) { }
- 
-   bool verify(const Function &F) {
-     M = F.getParent();
-@@ -538,8 +533,6 @@
- void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
-                                    const GlobalAlias &GA, const Constant &C) {
-   if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
--    Assert1(!GV->isDeclaration(), "Alias must point to a definition", &GA);
--
-     if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
-       Assert1(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA);
- 
---- lib/Linker/LinkModules.cpp	2015-02-24 18:00:21.000000000 -0800
-+++ lib/Linker/LinkModules.cpp	2015-12-07 12:26:23.891323205 -0800
-@@ -1194,7 +1194,7 @@
-     DI->setName(Arg.getName());  // Copy the name over.
- 
-     // Add a mapping to our mapping.
--    ValueMap[&Arg] = DI;
-+    ValueMap[&Arg] = &*DI;
-     ++DI;
-   }
- 
-@@ -1518,7 +1518,7 @@
-   // initializers (which could refer to functions not yet mapped over).
-   for (Module::global_iterator I = SrcM->global_begin(),
-        E = SrcM->global_end(); I != E; ++I)
--    if (linkGlobalValueProto(I))
-+    if (linkGlobalValueProto(&*I))
-       return true;
- 
-   // Link the functions together between the two modules, without doing function
-@@ -1527,13 +1527,13 @@
-   // all of the global values that may be referenced are available in our
-   // ValueMap.
-   for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
--    if (linkGlobalValueProto(I))
-+    if (linkGlobalValueProto(&*I))
-       return true;
- 
-   // If there were any aliases, link them now.
-   for (Module::alias_iterator I = SrcM->alias_begin(),
-        E = SrcM->alias_end(); I != E; ++I)
--    if (linkGlobalValueProto(I))
-+    if (linkGlobalValueProto(&*I))
-       return true;
- 
-   for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
---- lib/MC/MCAssembler.cpp	2015-01-16 16:38:54.000000000 -0800
-+++ lib/MC/MCAssembler.cpp	2015-12-07 12:37:47.486088108 -0800
-@@ -315,11 +315,13 @@
-     if (ExactMatch)
-       ++MI;
-   }
-+
-   iterator IP;
-   if (MI == SubsectionFragmentMap.end())
-     IP = end();
-   else
--    IP = MI->second;
-+    IP = MI->second->getIterator();
-+
-   if (!ExactMatch && Subsection != 0) {
-     // The GNU as documentation claims that subsections have an alignment of 4,
-     // although this appears not to be the case.
-@@ -892,7 +894,7 @@
-     // Create dummy fragments to eliminate any empty sections, this simplifies
-     // layout.
-     if (it->getFragmentList().empty())
--      new MCDataFragment(it);
-+      new MCDataFragment(&*it);
- 
-     it->setOrdinal(SectionIndex++);
-   }
-@@ -1091,7 +1093,7 @@
-       break;
-     }
-     if (RelaxedFrag && !FirstRelaxedFragment)
--      FirstRelaxedFragment = I;
-+      FirstRelaxedFragment = &*I;
-   }
-   if (FirstRelaxedFragment) {
-     Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
---- lib/MC/MCMachOStreamer.cpp	2014-09-17 02:25:36.000000000 -0700
-+++ lib/MC/MCMachOStreamer.cpp	2015-12-07 12:41:51.654959723 -0800
-@@ -444,7 +444,7 @@
-     MCSymbolData *CurrentAtom = nullptr;
-     for (MCSectionData::iterator it2 = it->begin(),
-            ie2 = it->end(); it2 != ie2; ++it2) {
--      if (MCSymbolData *SD = DefiningSymbolMap.lookup(it2))
-+      if (MCSymbolData *SD = DefiningSymbolMap.lookup(&*it2))
-         CurrentAtom = SD;
-       it2->setAtom(CurrentAtom);
-     }
---- lib/MC/MCObjectStreamer.cpp	2014-12-12 13:48:03.000000000 -0800
-+++ lib/MC/MCObjectStreamer.cpp	2015-12-07 12:52:20.758780735 -0800
-@@ -83,7 +83,7 @@
-   assert(getCurrentSectionData() && "No current section!");
- 
-   if (CurInsertionPoint != getCurrentSectionData()->getFragmentList().begin())
--    return std::prev(CurInsertionPoint);
-+    return &*std::prev(CurInsertionPoint);
- 
-   return nullptr;
- }
---- lib/MC/MachObjectWriter.cpp	2015-01-16 16:38:54.000000000 -0800
-+++ lib/MC/MachObjectWriter.cpp	2015-12-07 13:28:29.179917460 -0800
-@@ -839,9 +839,9 @@
-   uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
-   for (MCAssembler::const_iterator it = Asm.begin(),
-          ie = Asm.end(); it != ie; ++it) {
--    std::vector<MachO::any_relocation_info> &Relocs = Relocations[it];
-+    std::vector<MachO::any_relocation_info> &Relocs = Relocations[&*it];
-     unsigned NumRelocs = Relocs.size();
--    uint64_t SectionStart = SectionDataStart + getSectionAddress(it);
-+    uint64_t SectionStart = SectionDataStart + getSectionAddress(&*it);
-     WriteSection(Asm, Layout, *it, SectionStart, RelocTableEnd, NumRelocs);
-     RelocTableEnd += NumRelocs * sizeof(MachO::any_relocation_info);
-   }
-@@ -918,9 +918,9 @@
-   // Write the actual section data.
-   for (MCAssembler::const_iterator it = Asm.begin(),
-          ie = Asm.end(); it != ie; ++it) {
--    Asm.writeSectionData(it, Layout);
-+    Asm.writeSectionData(&*it, Layout);
- 
--    uint64_t Pad = getPaddingSize(it, Layout);
-+    uint64_t Pad = getPaddingSize(&*it, Layout);
-     for (unsigned int i = 0; i < Pad; ++i)
-       Write8(0);
-   }
-@@ -933,7 +933,7 @@
-          ie = Asm.end(); it != ie; ++it) {
-     // Write the section relocation entries, in reverse order to match 'as'
-     // (approximately, the exact algorithm is more complicated than this).
--    std::vector<MachO::any_relocation_info> &Relocs = Relocations[it];
-+    std::vector<MachO::any_relocation_info> &Relocs = Relocations[&*it];
-     for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
-       Write32(Relocs[e - i - 1].r_word0);
-       Write32(Relocs[e - i - 1].r_word1);
---- lib/MC/WinCOFFObjectWriter.cpp	2015-02-09 19:52:36.000000000 -0800
-+++ lib/MC/WinCOFFObjectWriter.cpp	2015-12-07 14:55:13.070245970 -0800
-@@ -1015,7 +1015,7 @@
-         assert(OS.tell() == (*i)->Header.PointerToRawData &&
-                "Section::PointerToRawData is insane!");
- 
--        Asm.writeSectionData(j, Layout);
-+        Asm.writeSectionData(&*j, Layout);
-       }
- 
-       if ((*i)->Relocations.size() > 0) {
---- lib/Support/YAMLParser.cpp	2014-08-30 09:48:02.000000000 -0700
-+++ lib/Support/YAMLParser.cpp	2015-11-27 18:09:35.106421600 -0800
-@@ -393,9 +393,10 @@
-   bool isBlankOrBreak(StringRef::iterator Position);
- 
-   /// @brief If IsSimpleKeyAllowed, create and push_back a new SimpleKey.
--  void saveSimpleKeyCandidate( TokenQueueT::iterator Tok
--                             , unsigned AtColumn
--                             , bool IsRequired);
-+  /// Please cut the comma placement bullshit. Thank you.
-+  void saveSimpleKeyCandidate(TokenQueueT::iterator Tok,
-+                              unsigned AtColumn,
-+                              bool IsRequired);
- 
-   /// @brief Remove simple keys that can no longer be valid simple keys.
-   ///
-@@ -742,7 +743,7 @@
- 
-     removeStaleSimpleKeyCandidates();
-     SimpleKey SK;
--    SK.Tok = TokenQueue.front();
-+    SK.Tok = TokenQueue.begin();
-     if (std::find(SimpleKeys.begin(), SimpleKeys.end(), SK)
-         == SimpleKeys.end())
-       break;
-@@ -896,9 +897,9 @@
-   return false;
- }
- 
--void Scanner::saveSimpleKeyCandidate( TokenQueueT::iterator Tok
--                                    , unsigned AtColumn
--                                    , bool IsRequired) {
-+void Scanner::saveSimpleKeyCandidate(TokenQueueT::iterator Tok,
-+                                     unsigned AtColumn,
-+                                     bool IsRequired) {
-   if (IsSimpleKeyAllowed) {
-     SimpleKey SK;
-     SK.Tok = Tok;
-@@ -1078,7 +1079,7 @@
-   TokenQueue.push_back(T);
- 
-   // [ and { may begin a simple key.
--  saveSimpleKeyCandidate(TokenQueue.back(), Column - 1, false);
-+  saveSimpleKeyCandidate(--TokenQueue.end(), Column - 1, false);
- 
-   // And may also be followed by a simple key.
-   IsSimpleKeyAllowed = true;
-@@ -1241,7 +1242,7 @@
-   T.Range = StringRef(Start, Current - Start);
-   TokenQueue.push_back(T);
- 
--  saveSimpleKeyCandidate(TokenQueue.back(), ColStart, false);
-+  saveSimpleKeyCandidate(--TokenQueue.end(), ColStart, false);
- 
-   IsSimpleKeyAllowed = false;
- 
-@@ -1319,7 +1320,7 @@
-   TokenQueue.push_back(T);
- 
-   // Plain scalars can be simple keys.
--  saveSimpleKeyCandidate(TokenQueue.back(), ColStart, false);
-+  saveSimpleKeyCandidate(--TokenQueue.end(), ColStart, false);
- 
-   IsSimpleKeyAllowed = false;
- 
-@@ -1354,7 +1355,7 @@
-   TokenQueue.push_back(T);
- 
-   // Alias and anchors can be simple keys.
--  saveSimpleKeyCandidate(TokenQueue.back(), ColStart, false);
-+  saveSimpleKeyCandidate(--TokenQueue.end(), ColStart, false);
- 
-   IsSimpleKeyAllowed = false;
- 
-@@ -1418,7 +1419,7 @@
-   TokenQueue.push_back(T);
- 
-   // Tags can be simple keys.
--  saveSimpleKeyCandidate(TokenQueue.back(), ColStart, false);
-+  saveSimpleKeyCandidate(--TokenQueue.end(), ColStart, false);
- 
-   IsSimpleKeyAllowed = false;
- 
---- lib/Target/Sparc/SparcAsmPrinter.cpp	2014-08-04 14:25:23.000000000 -0700
-+++ lib/Target/Sparc/SparcAsmPrinter.cpp	2015-12-07 11:54:08.441400090 -0800
-@@ -267,11 +267,11 @@
-     LowerGETPCXAndEmitMCInsts(MI, getSubtargetInfo());
-     return;
-   }
--  MachineBasicBlock::const_instr_iterator I = MI;
-+  MachineBasicBlock::const_instr_iterator I = MI->getIterator();
-   MachineBasicBlock::const_instr_iterator E = MI->getParent()->instr_end();
-   do {
-     MCInst TmpInst;
--    LowerSparcMachineInstrToMCInst(I, TmpInst, *this);
-+    LowerSparcMachineInstrToMCInst(&*I, TmpInst, *this);
-     EmitToStreamer(OutStreamer, TmpInst);
-   } while ((++I != E) && I->isInsideBundle()); // Delay slot check.
- }
---- lib/Target/Sparc/SparcISelLowering.cpp	2015-01-07 16:51:32.000000000 -0800
-+++ lib/Target/Sparc/SparcISelLowering.cpp	2015-12-07 11:59:14.697760005 -0800
-@@ -2916,8 +2916,7 @@
-   // to set, the condition code register to branch on, the true/false values to
-   // select between, and a branch opcode to use.
-   const BasicBlock *LLVM_BB = BB->getBasicBlock();
--  MachineFunction::iterator It = BB;
--  ++It;
-+  MachineFunction::iterator It = ++BB->getIterator();
- 
-   //  thisMBB:
-   //  ...
-@@ -3003,7 +3002,7 @@
-     .addReg(AddrReg).addImm(0);
- 
-   // Split the basic block MBB before MI and insert the loop block in the hole.
--  MachineFunction::iterator MFI = MBB;
-+  MachineFunction::iterator MFI = MBB->getIterator();
-   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
-   MachineFunction *MF = MBB->getParent();
-   MachineBasicBlock *LoopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
---- lib/Target/Sparc/SparcTargetObjectFile.cpp	2014-04-24 22:30:21.000000000 -0700
-+++ lib/Target/Sparc/SparcTargetObjectFile.cpp	2015-12-15 12:44:57.569902985 -0800
-@@ -15,6 +15,17 @@
- 
- using namespace llvm;
- 
-+void SparcELFTargetObjectFile::Initialize(MCContext &CTX,
-+                                          const TargetMachine &TM) {
-+  TargetLoweringObjectFile::Initialize(CTX, TM);
-+  std::string OS = TM.getTargetTriple().str();
-+
-+  if (OS.find("solaris") != std::string::npos)
-+    InitializeELF(true);
-+  else
-+    InitializeELF(TM.Options.UseInitArray);
-+}
-+
- const MCExpr *SparcELFTargetObjectFile::getTTypeGlobalReference(
-     const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
-     const TargetMachine &TM, MachineModuleInfo *MMI,
---- lib/Target/Sparc/SparcTargetObjectFile.h	2014-08-13 09:26:38.000000000 -0700
-+++ lib/Target/Sparc/SparcTargetObjectFile.h	2015-12-15 12:37:54.653197100 -0800
-@@ -19,11 +19,11 @@
- 
- class SparcELFTargetObjectFile : public TargetLoweringObjectFileELF {
- public:
--  SparcELFTargetObjectFile() :
--    TargetLoweringObjectFileELF()
--  {}
-+  SparcELFTargetObjectFile() : TargetLoweringObjectFileELF() { }
- 
--  const MCExpr *
-+  virtual void Initialize(MCContext &CTX, const TargetMachine &TM) override;
-+
-+  const MCExpr*
-   getTTypeGlobalReference(const GlobalValue *GV, unsigned Encoding,
-                           Mangler &Mang, const TargetMachine &TM,
-                           MachineModuleInfo *MMI,
---- lib/Target/X86/X86FastISel.cpp	2015-01-05 23:35:50.000000000 -0800
-+++ lib/Target/X86/X86FastISel.cpp	2016-01-23 08:58:44.000000000 -0800
-@@ -275,8 +275,8 @@
-     return false;
- 
-   // Make sure nothing is in the way
--  BasicBlock::const_iterator Start = I;
--  BasicBlock::const_iterator End = II;
-+  BasicBlock::const_iterator Start(I);
-+  BasicBlock::const_iterator End(II);
-   for (auto Itr = std::prev(Start); Itr != End; --Itr) {
-     // We only expect extractvalue instructions between the intrinsic and the
-     // instruction to be selected.
---- lib/Target/X86/X86FixupLEAs.cpp	2015-01-05 02:15:49.000000000 -0800
-+++ lib/Target/X86/X86FixupLEAs.cpp	2016-01-23 08:57:43.000000000 -0800
-@@ -190,7 +190,7 @@
- static inline bool getPreviousInstr(MachineBasicBlock::iterator &I,
-                                     MachineFunction::iterator MFI) {
-   if (I == MFI->begin()) {
--    if (MFI->isPredecessor(MFI)) {
-+    if (MFI->isPredecessor(&*MFI)) {
-       I = --MFI->end();
-       return true;
-     } else
---- lib/Target/X86/X86FloatingPoint.cpp	2014-11-18 23:49:26.000000000 -0800
-+++ lib/Target/X86/X86FloatingPoint.cpp	2016-01-23 09:03:48.000000000 -0800
-@@ -321,7 +321,7 @@
-   // Process the function in depth first order so that we process at least one
-   // of the predecessors for every reachable block in the function.
-   SmallPtrSet<MachineBasicBlock*, 8> Processed;
--  MachineBasicBlock *Entry = MF.begin();
-+  MachineBasicBlock *Entry = &MF.front();
- 
-   bool Changed = false;
-   for (MachineBasicBlock *BB : depth_first_ext(Entry, Processed))
-@@ -329,9 +329,9 @@
- 
-   // Process any unreachable blocks in arbitrary order now.
-   if (MF.size() != Processed.size())
--    for (MachineFunction::iterator BB = MF.begin(), E = MF.end(); BB != E; ++BB)
--      if (Processed.insert(BB).second)
--        Changed |= processBasicBlock(MF, *BB);
-+    for (MachineBasicBlock &BB : MF)
-+      if (Processed.insert(&BB).second)
-+        Changed |= processBasicBlock(MF, BB);
- 
-   LiveBundles.clear();
- 
-@@ -348,13 +348,12 @@
-   LiveBundles.resize(Bundles->getNumBundles());
- 
-   // Gather the actual live-in masks for all MBBs.
--  for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
--    MachineBasicBlock *MBB = I;
--    const unsigned Mask = calcLiveInMask(MBB);
-+  for (MachineBasicBlock &MBB : MF) {
-+    const unsigned Mask = calcLiveInMask(&MBB);
-     if (!Mask)
-       continue;
-     // Update MBB ingoing bundle mask.
--    LiveBundles[Bundles->getBundle(MBB->getNumber(), false)].Mask |= Mask;
-+    LiveBundles[Bundles->getBundle(MBB.getNumber(), false)].Mask |= Mask;
-   }
- }
- 
---- lib/Target/X86/X86ISelDAGToDAG.cpp	2015-01-05 20:23:53.000000000 -0800
-+++ lib/Target/X86/X86ISelDAGToDAG.cpp	2016-01-23 09:08:15.000000000 -0800
-@@ -458,7 +458,8 @@
- 
-   for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
-        E = CurDAG->allnodes_end(); I != E; ) {
--    SDNode *N = I++;  // Preincrement iterator to avoid invalidation issues.
-+    SDNode *N = &*I;  // Preincrement iterator to avoid invalidation issues.
-+    ++I;
- 
-     if (OptLevel != CodeGenOpt::None &&
-         // Only does this when target favors doesn't favor register indirect
-@@ -586,7 +587,7 @@
-   // If this is main, emit special code for main.
-   if (const Function *Fn = MF->getFunction())
-     if (Fn->hasExternalLinkage() && Fn->getName() == "main")
--      EmitSpecialCodeForMain(MF->begin(), MF->getFrameInfo());
-+      EmitSpecialCodeForMain(&MF->front(), MF->getFrameInfo());
- }
- 
- static bool isDispSafeForFrameIndex(int64_t Val) {
-@@ -778,7 +779,7 @@
- static void InsertDAGNode(SelectionDAG &DAG, SDValue Pos, SDValue N) {
-   if (N.getNode()->getNodeId() == -1 ||
-       N.getNode()->getNodeId() > Pos.getNode()->getNodeId()) {
--    DAG.RepositionNode(Pos.getNode(), N.getNode());
-+    DAG.RepositionNode(Pos.getNode()->getIterator(), N.getNode());
-     N.getNode()->setNodeId(Pos.getNode()->getNodeId());
-   }
- }
---- lib/Target/X86/X86ISelLowering.cpp	2015-05-01 21:17:29.000000000 -0700
-+++ lib/Target/X86/X86ISelLowering.cpp	2016-01-23 10:03:26.000000000 -0800
-@@ -20363,8 +20363,7 @@
-   DebugLoc DL = MI->getDebugLoc();
- 
-   const BasicBlock *BB = MBB->getBasicBlock();
--  MachineFunction::iterator I = MBB;
--  ++I;
-+  MachineFunction::iterator I = ++MBB->getIterator();
- 
-   // For the v = xbegin(), we generate
-   //
-@@ -20613,7 +20612,7 @@
-     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
-     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
- 
--    MachineFunction::iterator MBBIter = MBB;
-+    MachineFunction::iterator MBBIter = ++MBB->getIterator();
-     ++MBBIter;
- 
-     // Insert the new basic blocks
-@@ -20784,8 +20783,7 @@
-   // stores were performed.
-   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
-   MachineFunction *F = MBB->getParent();
--  MachineFunction::iterator MBBIter = MBB;
--  ++MBBIter;
-+  MachineFunction::iterator MBBIter = ++MBB->getIterator();
-   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
-   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
-   F->insert(MBBIter, XMMSaveMBB);
-@@ -20893,8 +20891,7 @@
-   // destination vreg to set, the condition code register to branch on, the
-   // true/false values to select between, and a branch opcode to use.
-   const BasicBlock *LLVM_BB = BB->getBasicBlock();
--  MachineFunction::iterator It = BB;
--  ++It;
-+  MachineFunction::iterator It = ++BB->getIterator();
- 
-   //  thisMBB:
-   //  ...
-@@ -20997,8 +20994,7 @@
-     sizeVReg = MI->getOperand(1).getReg(),
-     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
- 
--  MachineFunction::iterator MBBIter = BB;
--  ++MBBIter;
-+  MachineFunction::iterator MBBIter = ++BB->getIterator();
- 
-   MF->insert(MBBIter, bumpMBB);
-   MF->insert(MBBIter, mallocMBB);
-@@ -21168,8 +21164,7 @@
-   MachineRegisterInfo &MRI = MF->getRegInfo();
- 
-   const BasicBlock *BB = MBB->getBasicBlock();
--  MachineFunction::iterator I = MBB;
--  ++I;
-+  MachineFunction::iterator I = ++MBB->getIterator();
- 
-   // Memory Reference
-   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
---- lib/Target/X86/X86PadShortFunction.cpp	2014-08-04 14:25:23.000000000 -0700
-+++ lib/Target/X86/X86PadShortFunction.cpp	2016-01-23 10:05:38.000000000 -0800
-@@ -110,7 +110,7 @@
-   // Search through basic blocks and mark the ones that have early returns
-   ReturnBBs.clear();
-   VisitedBBs.clear();
--  findReturns(MF.begin());
-+  findReturns(&MF.front());
- 
-   bool MadeChange = false;
- 
---- lib/Transforms/IPO/ArgumentPromotion.cpp	2014-12-15 06:09:53.000000000 -0800
-+++ lib/Transforms/IPO/ArgumentPromotion.cpp	2015-11-29 18:37:06.014532943 -0800
-@@ -214,7 +214,8 @@
-   SmallVector<Argument*, 16> PointerArgs;
-   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
-     if (I->getType()->isPointerTy())
--      PointerArgs.push_back(I);
-+      PointerArgs.push_back(&*I);
-+
-   if (PointerArgs.empty()) return nullptr;
- 
-   // Second check: make sure that all callers are direct callers.  We can't
-@@ -435,7 +436,8 @@
- 
-   // First, iterate the entry block and mark loads of (geps of) arguments as
-   // safe.
--  BasicBlock *EntryBlock = Arg->getParent()->begin();
-+  BasicBlock *EntryBlock = &Arg->getParent()->front();
-+
-   // Declare this here so we can reuse it
-   IndicesVector Indices;
-   for (BasicBlock::iterator I = EntryBlock->begin(), E = EntryBlock->end();
-@@ -620,14 +622,14 @@
-   unsigned ArgIndex = 1;
-   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E;
-        ++I, ++ArgIndex) {
--    if (ByValArgsToTransform.count(I)) {
-+    if (ByValArgsToTransform.count(&*I)) {
-       // Simple byval argument? Just add all the struct element types.
-       Type *AgTy = cast<PointerType>(I->getType())->getElementType();
-       StructType *STy = cast<StructType>(AgTy);
-       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
-         Params.push_back(STy->getElementType(i));
-       ++NumByValArgsPromoted;
--    } else if (!ArgsToPromote.count(I)) {
-+    } else if (!ArgsToPromote.count(&*I)) {
-       // Unchanged argument
-       Params.push_back(I->getType());
-       AttributeSet attrs = PAL.getParamAttributes(ArgIndex);
-@@ -645,7 +647,7 @@
- 
-       // In this table, we will track which indices are loaded from the argument
-       // (where direct loads are tracked as no indices).
--      ScalarizeTable &ArgIndices = ScalarizedElements[I];
-+      ScalarizeTable &ArgIndices = ScalarizedElements[&*I];
-       for (User *U : I->users()) {
-         Instruction *UI = cast<Instruction>(U);
-         assert(isa<LoadInst>(UI) || isa<GetElementPtrInst>(UI));
-@@ -667,7 +669,7 @@
-         else
-           // Take any load, we will use it only to update Alias Analysis
-           OrigLoad = cast<LoadInst>(UI->user_back());
--        OriginalLoads[std::make_pair(I, Indices)] = OrigLoad;
-+        OriginalLoads[std::make_pair(&*I, Indices)] = OrigLoad;
-       }
- 
-       // Add a parameter to the function for each element passed in.
-@@ -712,19 +714,15 @@
- 
-   DEBUG(dbgs() << "ARG PROMOTION:  Promoting to:" << *NF << "\n"
-         << "From: " << *F);
--  
-+
-   // Recompute the parameter attributes list based on the new arguments for
-   // the function.
-   NF->setAttributes(AttributeSet::get(F->getContext(), AttributesVec));
-   AttributesVec.clear();
- 
--  F->getParent()->getFunctionList().insert(F, NF);
-+  F->getParent()->getFunctionList().insert(F->getIterator(), NF);
-   NF->takeName(F);
- 
--  // Get the alias analysis information that we need to update to reflect our
--  // changes.
--  AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
--
-   // Get the callgraph information that we need to update to reflect our
-   // changes.
-   CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
-@@ -753,7 +751,7 @@
-     ArgIndex = 1;
-     for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
-          I != E; ++I, ++AI, ++ArgIndex)
--      if (!ArgsToPromote.count(I) && !ByValArgsToTransform.count(I)) {
-+      if (!ArgsToPromote.count(&*I) && !ByValArgsToTransform.count(&*I)) {
-         Args.push_back(*AI);          // Unmodified argument
- 
-         if (CallPAL.hasAttributes(ArgIndex)) {
-@@ -761,7 +759,7 @@
-           AttributesVec.
-             push_back(AttributeSet::get(F->getContext(), Args.size(), B));
-         }
--      } else if (ByValArgsToTransform.count(I)) {
-+      } else if (ByValArgsToTransform.count(&*I)) {
-         // Emit a GEP and load for each element of the struct.
-         Type *AgTy = cast<PointerType>(I->getType())->getElementType();
-         StructType *STy = cast<StructType>(AgTy);
-@@ -777,14 +775,14 @@
-         }
-       } else if (!I->use_empty()) {
-         // Non-dead argument: insert GEPs and loads as appropriate.
--        ScalarizeTable &ArgIndices = ScalarizedElements[I];
-+        ScalarizeTable &ArgIndices = ScalarizedElements[&*I];
-         // Store the Value* version of the indices in here, but declare it now
-         // for reuse.
-         std::vector<Value*> Ops;
-         for (ScalarizeTable::iterator SI = ArgIndices.begin(),
-                E = ArgIndices.end(); SI != E; ++SI) {
-           Value *V = *AI;
--          LoadInst *OrigLoad = OriginalLoads[std::make_pair(I, *SI)];
-+          LoadInst *OrigLoad = OriginalLoads[std::make_pair(&*I, *SI)];
-           if (!SI->empty()) {
-             Ops.reserve(SI->size());
-             Type *ElTy = V->getType();
-@@ -793,7 +791,7 @@
-               // Use i32 to index structs, and i64 for others (pointers/arrays).
-               // This satisfies GEP constraints.
-               Type *IdxTy = (ElTy->isStructTy() ?
--                    Type::getInt32Ty(F->getContext()) : 
-+                    Type::getInt32Ty(F->getContext()) :
-                     Type::getInt64Ty(F->getContext()));
-               Ops.push_back(ConstantInt::get(IdxTy, *II));
-               // Keep track of the type we're currently indexing.
-@@ -802,8 +800,8 @@
-             // And create a GEP to extract those indices.
-             V = GetElementPtrInst::Create(V, Ops, V->getName()+".idx", Call);
-             Ops.clear();
--            AA.copyValue(OrigLoad->getOperand(0), V);
-           }
-+
-           // Since we're replacing a load make sure we take the alignment
-           // of the previous load.
-           LoadInst *newLoad = new LoadInst(V, V->getName()+".val", Call);
-@@ -814,7 +812,6 @@
-           newLoad->setAAMetadata(AAInfo);
- 
-           Args.push_back(newLoad);
--          AA.copyValue(OrigLoad, Args.back());
-         }
-       }
- 
-@@ -852,10 +849,6 @@
-     Args.clear();
-     AttributesVec.clear();
- 
--    // Update the alias analysis implementation to know that we are replacing
--    // the old call with a new one.
--    AA.replaceWithNewValue(Call, New);
--
-     // Update the callgraph to know that the callsite has been transformed.
-     CallGraphNode *CalleeNode = CG[Call->getParent()->getParent()];
-     CalleeNode->replaceCallEdge(Call, New, NF_CGN);
-@@ -877,23 +870,21 @@
- 
-   // Loop over the argument list, transferring uses of the old arguments over to
-   // the new arguments, also transferring over the names as well.
--  //
-   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
-        I2 = NF->arg_begin(); I != E; ++I) {
--    if (!ArgsToPromote.count(I) && !ByValArgsToTransform.count(I)) {
-+    if (!ArgsToPromote.count(&*I) && !ByValArgsToTransform.count(&*I)) {
-       // If this is an unmodified argument, move the name and users over to the
-       // new version.
--      I->replaceAllUsesWith(I2);
--      I2->takeName(I);
--      AA.replaceWithNewValue(I, I2);
-+      I->replaceAllUsesWith(&*I2);
-+      I2->takeName(&*I);
-       ++I2;
-       continue;
-     }
- 
--    if (ByValArgsToTransform.count(I)) {
-+    if (ByValArgsToTransform.count(&*I)) {
-       // In the callee, we create an alloca, and store each of the new incoming
-       // arguments into the alloca.
--      Instruction *InsertPt = NF->begin()->begin();
-+      Instruction *InsertPt = &NF->begin()->front();
- 
-       // Just add all the struct element types.
-       Type *AgTy = cast<PointerType>(I->getType())->getElementType();
-@@ -904,18 +895,17 @@
- 
-       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
-         Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i);
--        Value *Idx = 
-+        Value *Idx =
-           GetElementPtrInst::Create(TheAlloca, Idxs,
--                                    TheAlloca->getName()+"."+Twine(i), 
-+                                    TheAlloca->getName() + "." + Twine(i),
-                                     InsertPt);
--        I2->setName(I->getName()+"."+Twine(i));
--        new StoreInst(I2++, Idx, InsertPt);
-+        I2->setName(I->getName() + "." +Twine(i));
-+        new StoreInst(&*I2++, Idx, InsertPt);
-       }
- 
-       // Anything that used the arg should now use the alloca.
-       I->replaceAllUsesWith(TheAlloca);
--      TheAlloca->takeName(I);
--      AA.replaceWithNewValue(I, TheAlloca);
-+      TheAlloca->takeName(&*I);
- 
-       // If the alloca is used in a call, we must clear the tail flag since
-       // the callee now uses an alloca from the caller.
-@@ -928,23 +918,20 @@
-       continue;
-     }
- 
--    if (I->use_empty()) {
--      AA.deleteValue(I);
-+    if (I->use_empty())
-       continue;
--    }
- 
-     // Otherwise, if we promoted this argument, then all users are load
-     // instructions (or GEPs with only load users), and all loads should be
-     // using the new argument that we added.
--    ScalarizeTable &ArgIndices = ScalarizedElements[I];
-+    ScalarizeTable &ArgIndices = ScalarizedElements[&*I];
- 
-     while (!I->use_empty()) {
-       if (LoadInst *LI = dyn_cast<LoadInst>(I->user_back())) {
-         assert(ArgIndices.begin()->empty() &&
-                "Load element should sort to front!");
-         I2->setName(I->getName()+".val");
--        LI->replaceAllUsesWith(I2);
--        AA.replaceWithNewValue(LI, I2);
-+        LI->replaceAllUsesWith(&*I2);
-         LI->eraseFromParent();
-         DEBUG(dbgs() << "*** Promoted load of argument '" << I->getName()
-               << "' in function '" << F->getName() << "'\n");
-@@ -980,11 +967,10 @@
-         // the argument specified by ArgNo.
-         while (!GEP->use_empty()) {
-           LoadInst *L = cast<LoadInst>(GEP->user_back());
--          L->replaceAllUsesWith(TheArg);
--          AA.replaceWithNewValue(L, TheArg);
-+          L->replaceAllUsesWith(&*TheArg);
-           L->eraseFromParent();
-         }
--        AA.deleteValue(GEP);
-+
-         GEP->eraseFromParent();
-       }
-     }
-@@ -993,12 +979,9 @@
-     std::advance(I2, ArgIndices.size());
-   }
- 
--  // Tell the alias analysis that the old function is about to disappear.
--  AA.replaceWithNewValue(F, NF);
- 
--  
-   NF_CGN->stealCalledFunctionsFrom(CG[F]);
--  
-+
-   // Now that the old function is dead, delete it.  If there is a dangling
-   // reference to the CallgraphNode, just leave the dead function around for
-   // someone else to nuke.
-@@ -1007,7 +990,7 @@
-     delete CG.removeFunctionFromModule(CGN);
-   else
-     F->setLinkage(Function::ExternalLinkage);
--  
-+
-   return NF_CGN;
- }
- 
---- lib/Transforms/IPO/ConstantMerge.cpp	2014-08-20 22:55:13.000000000 -0700
-+++ lib/Transforms/IPO/ConstantMerge.cpp	2015-11-29 18:38:45.961868975 -0800
-@@ -130,7 +130,8 @@
-     // First: Find the canonical constants others will be merged with.
-     for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
-          GVI != E; ) {
--      GlobalVariable *GV = GVI++;
-+      GlobalVariable *GV = &*GVI;
-+      ++GVI;
- 
-       // If this GV is dead, remove it.
-       GV->removeDeadConstantUsers();
-@@ -172,7 +173,8 @@
-     // invalidating the Constant* pointers in CMap.
-     for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
-          GVI != E; ) {
--      GlobalVariable *GV = GVI++;
-+      GlobalVariable *GV = &*GVI;
-+      ++GVI;
- 
-       // Only process constants with initializers in the default address space.
-       if (!GV->isConstant() || !GV->hasDefinitiveInitializer() ||
---- lib/Transforms/IPO/DeadArgumentElimination.cpp	2014-10-07 08:10:23.000000000 -0700
-+++ lib/Transforms/IPO/DeadArgumentElimination.cpp	2015-11-29 18:53:45.446590015 -0800
-@@ -229,7 +229,7 @@
-   // Create the new function body and insert it into the module...
-   Function *NF = Function::Create(NFTy, Fn.getLinkage());
-   NF->copyAttributesFrom(&Fn);
--  Fn.getParent()->getFunctionList().insert(&Fn, NF);
-+  Fn.getParent()->getFunctionList().insert(Fn.getIterator(), NF);
-   NF->takeName(&Fn);
- 
-   // Loop over all of the callers of the function, transforming the call sites
-@@ -296,8 +296,8 @@
-   for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(),
-        I2 = NF->arg_begin(); I != E; ++I, ++I2) {
-     // Move the name and users over to the new version.
--    I->replaceAllUsesWith(I2);
--    I2->takeName(I);
-+    I->replaceAllUsesWith(&*I2);
-+    I2->takeName(&*I);
-   }
- 
-   // Patch the pointer to LLVM function in debug info descriptor.
-@@ -351,12 +351,10 @@
-     return false;
- 
-   SmallVector<unsigned, 8> UnusedArgs;
--  for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(); 
--       I != E; ++I) {
--    Argument *Arg = I;
- 
--    if (Arg->use_empty() && !Arg->hasByValOrInAllocaAttr())
--      UnusedArgs.push_back(Arg->getArgNo());
-+  for (Argument &Arg : Fn.args()) {
-+    if (Arg.use_empty() && !Arg.hasByValOrInAllocaAttr())
-+      UnusedArgs.push_back(Arg.getArgNo());
-   }
- 
-   if (UnusedArgs.empty())
-@@ -617,7 +615,7 @@
-     } else {
-       // See what the effect of this use is (recording any uses that cause
-       // MaybeLive in MaybeLiveArgUses). 
--      Result = SurveyUses(AI, MaybeLiveArgUses);
-+      Result = SurveyUses(&*AI, MaybeLiveArgUses);
-     }
- 
-     // Mark the result.
-@@ -862,7 +860,7 @@
-   NF->setAttributes(NewPAL);
-   // Insert the new function before the old function, so we won't be processing
-   // it again.
--  F->getParent()->getFunctionList().insert(F, NF);
-+  F->getParent()->getFunctionList().insert(F->getIterator(), NF);
-   NF->takeName(F);
- 
-   // Loop over all of the callers of the function, transforming the call sites
-@@ -966,7 +964,7 @@
-         if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
-           BasicBlock::iterator IP = II->getNormalDest()->begin();
-           while (isa<PHINode>(IP)) ++IP;
--          InsertPt = IP;
-+          InsertPt = &*IP;
-         }
- 
-         // We used to return a struct. Instead of doing smart stuff with all the
-@@ -1014,8 +1012,8 @@
-     if (ArgAlive[i]) {
-       // If this is a live argument, move the name and users over to the new
-       // version.
--      I->replaceAllUsesWith(I2);
--      I2->takeName(I);
-+      I->replaceAllUsesWith(&*I2);
-+      I2->takeName(&*I);
-       ++I2;
-     } else {
-       // If this argument is dead, replace any uses of it with null constants
-@@ -1107,7 +1105,8 @@
-   for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
-     // Increment now, because the function will probably get removed (ie.
-     // replaced by a new one).
--    Function *F = I++;
-+    Function *F = &*I;
-+    ++I;
-     Changed |= RemoveDeadStuffFromFunction(F);
-   }
- 
---- lib/Transforms/IPO/ExtractGV.cpp	2014-10-28 04:54:52.000000000 -0700
-+++ lib/Transforms/IPO/ExtractGV.cpp	2015-11-29 18:57:50.191073612 -0800
-@@ -83,7 +83,7 @@
-       for (Module::global_iterator I = M.global_begin(), E = M.global_end();
-            I != E; ++I) {
-         bool Delete =
--          deleteStuff == (bool)Named.count(I) && !I->isDeclaration();
-+          deleteStuff == (bool) Named.count(&*I) && !I->isDeclaration();
-         if (!Delete) {
-           if (I->hasAvailableExternallyLinkage())
-             continue;
-@@ -100,7 +100,7 @@
-       // Visit the Functions.
-       for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
-         bool Delete =
--          deleteStuff == (bool)Named.count(I) && !I->isDeclaration();
-+          deleteStuff == (bool) Named.count(&*I) && !I->isDeclaration();
-         if (!Delete) {
-           if (I->hasAvailableExternallyLinkage())
-             continue;
-@@ -108,8 +108,10 @@
- 
-         makeVisible(*I, Delete);
- 
--        if (Delete)
-+        if (Delete) {
-           I->deleteBody();
-+          I->setComdat(nullptr);
-+        }
-       }
- 
-       // Visit the Aliases.
-@@ -118,7 +120,7 @@
-         Module::alias_iterator CurI = I;
-         ++I;
- 
--        bool Delete = deleteStuff == (bool)Named.count(CurI);
-+        bool Delete = deleteStuff == (bool) Named.count(&*CurI);
-         makeVisible(*CurI, Delete);
- 
-         if (Delete) {
-@@ -136,8 +138,9 @@
-                                  nullptr, CurI->getName());
- 
-           }
-+
-           CurI->replaceAllUsesWith(Declaration);
--          delete CurI;
-+          delete &*CurI;
-         }
-       }
- 
---- lib/Transforms/IPO/FunctionAttrs.cpp	2014-11-18 23:49:26.000000000 -0800
-+++ lib/Transforms/IPO/FunctionAttrs.cpp	2015-11-29 19:01:30.757096968 -0800
-@@ -365,7 +365,7 @@
-           return true;
-         }
-         if (PI == U) {
--          Uses.push_back(AI);
-+          Uses.push_back(&*AI);
-           Found = true;
-           break;
-         }
-@@ -489,15 +489,19 @@
-                    "More params than args in non-varargs call.");
-             return Attribute::None;
-           }
-+
-           Captures &= !CS.doesNotCapture(A - B);
--          if (SCCNodes.count(AI))
-+          if (SCCNodes.count(&*AI))
-             continue;
-+
-           if (!CS.onlyReadsMemory() && !CS.onlyReadsMemory(A - B))
-             return Attribute::None;
-+
-           if (!CS.doesNotAccessMemory(A - B))
-             IsRead = true;
-         }
-       }
-+
-       AddUsersToWorklistIfCapturing();
-       break;
-     }
-@@ -574,7 +578,7 @@
-       bool HasNonLocalUses = false;
-       if (!A->hasNoCaptureAttr()) {
-         ArgumentUsesTracker Tracker(SCCNodes);
--        PointerMayBeCaptured(A, &Tracker);
-+        PointerMayBeCaptured(&*A, &Tracker);
-         if (!Tracker.Captured) {
-           if (Tracker.Uses.empty()) {
-             // If it's trivially not captured, mark it nocapture now.
-@@ -585,7 +589,7 @@
-             // If it's not trivially captured and not trivially not captured,
-             // then it must be calling into another function in our SCC. Save
-             // its particulars for Argument-SCC analysis later.
--            ArgumentGraphNode *Node = AG[A];
-+            ArgumentGraphNode *Node = AG[&*A];
-             for (SmallVectorImpl<Argument*>::iterator UI = Tracker.Uses.begin(),
-                      UE = Tracker.Uses.end(); UI != UE; ++UI) {
-               Node->Uses.push_back(AG[*UI]);
-@@ -602,8 +606,8 @@
-         // will be dependent on the iteration order through the functions in the
-         // SCC.
-         SmallPtrSet<Argument*, 8> Self;
--        Self.insert(A);
--        Attribute::AttrKind R = determinePointerReadAttrs(A, Self);
-+        Self.insert(&*A);
-+        Attribute::AttrKind R = determinePointerReadAttrs(&*A, Self);
-         if (R != Attribute::None) {
-           AttrBuilder B;
-           B.addAttribute(R);
---- lib/Transforms/IPO/GlobalDCE.cpp	2014-12-02 18:08:38.000000000 -0800
-+++ lib/Transforms/IPO/GlobalDCE.cpp	2015-11-29 19:08:57.774680942 -0800
-@@ -84,7 +84,7 @@
-     // Functions with external linkage are needed if they have a body
-     if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage()) {
-       if (!I->isDiscardableIfUnused())
--        GlobalIsNeeded(I);
-+        GlobalIsNeeded(&*I);
-     }
-   }
- 
-@@ -95,7 +95,7 @@
-     // initializer.
-     if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage()) {
-       if (!I->isDiscardableIfUnused())
--        GlobalIsNeeded(I);
-+        GlobalIsNeeded(&*I);
-     }
-   }
- 
-@@ -104,7 +104,7 @@
-     Changed |= RemoveUnusedGlobalValue(*I);
-     // Externally visible aliases are needed.
-     if (!I->isDiscardableIfUnused()) {
--      GlobalIsNeeded(I);
-+      GlobalIsNeeded(&*I);
-     }
-   }
- 
-@@ -116,8 +116,8 @@
-   std::vector<GlobalVariable*> DeadGlobalVars;   // Keep track of dead globals
-   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
-        I != E; ++I)
--    if (!AliveGlobals.count(I)) {
--      DeadGlobalVars.push_back(I);         // Keep track of dead globals
-+    if (!AliveGlobals.count(&*I)) {
-+      DeadGlobalVars.push_back(&*I);         // Keep track of dead globals
-       if (I->hasInitializer()) {
-         Constant *Init = I->getInitializer();
-         I->setInitializer(nullptr);
-@@ -129,8 +129,8 @@
-   // The second pass drops the bodies of functions which are dead...
-   std::vector<Function*> DeadFunctions;
-   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
--    if (!AliveGlobals.count(I)) {
--      DeadFunctions.push_back(I);         // Keep track of dead globals
-+    if (!AliveGlobals.count(&*I)) {
-+      DeadFunctions.push_back(&*I);         // Keep track of dead globals
-       if (!I->isDeclaration())
-         I->deleteBody();
-     }
-@@ -139,8 +139,8 @@
-   std::vector<GlobalAlias*> DeadAliases;
-   for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end(); I != E;
-        ++I)
--    if (!AliveGlobals.count(I)) {
--      DeadAliases.push_back(I);
-+    if (!AliveGlobals.count(&*I)) {
-+      DeadAliases.push_back(&*I);
-       I->setAliasee(nullptr);
-     }
- 
---- lib/Transforms/IPO/GlobalOpt.cpp	2014-11-18 23:49:26.000000000 -0800
-+++ lib/Transforms/IPO/GlobalOpt.cpp	2015-11-29 19:20:51.649538813 -0800
-@@ -493,12 +493,13 @@
-     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
-       Constant *In = Init->getAggregateElement(i);
-       assert(In && "Couldn't get element of initializer?");
--      GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
--                                               GlobalVariable::InternalLinkage,
--                                               In, GV->getName()+"."+Twine(i),
--                                               GV->getThreadLocalMode(),
--                                              GV->getType()->getAddressSpace());
--      Globals.insert(GV, NGV);
-+      GlobalVariable *NGV =
-+        new GlobalVariable(STy->getElementType(i), false,
-+                           GlobalVariable::InternalLinkage,
-+                           In, GV->getName()+"."+Twine(i),
-+                           GV->getThreadLocalMode(),
-+                           GV->getType()->getAddressSpace());
-+      Globals.insert(GV->getIterator(), NGV);
-       NewGlobals.push_back(NGV);
- 
-       // Calculate the known alignment of the field.  If theinal aggregate
-@@ -526,12 +527,13 @@
-       Constant *In = Init->getAggregateElement(i);
-       assert(In && "Couldn't get element of initializer?");
- 
--      GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
--                                               GlobalVariable::InternalLinkage,
--                                               In, GV->getName()+"."+Twine(i),
--                                               GV->getThreadLocalMode(),
--                                              GV->getType()->getAddressSpace());
--      Globals.insert(GV, NGV);
-+      GlobalVariable *NGV =
-+        new GlobalVariable(STy->getElementType(), false,
-+                           GlobalVariable::InternalLinkage,
-+                           In, GV->getName()+"."+Twine(i),
-+                           GV->getThreadLocalMode(),
-+                           GV->getType()->getAddressSpace());
-+      Globals.insert(GV->getIterator(), NGV);
-       NewGlobals.push_back(NGV);
- 
-       // Calculate the known alignment of the field.  If theinal aggregate
-@@ -936,7 +938,7 @@
-       cast<StoreInst>(InitBool->user_back())->eraseFromParent();
-     delete InitBool;
-   } else
--    GV->getParent()->getGlobalList().insert(GV, InitBool);
-+    GV->getParent()->getGlobalList().insert(GV->getIterator(), InitBool);
- 
-   // Now the GV is dead, nuke it and the malloc..
-   GV->eraseFromParent();
-@@ -1338,7 +1340,8 @@
- 
-   // Split the basic block at the old malloc.
-   BasicBlock *OrigBB = CI->getParent();
--  BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
-+  BasicBlock *ContBB =
-+    OrigBB->splitBasicBlock(CI->getIterator(), "malloc_cont");
- 
-   // Create the block to check the first condition.  Put all these blocks at the
-   // end of the function as they are unlikely to be executed.
-@@ -1505,7 +1508,8 @@
-     // (2048 bytes currently), as we don't want to introduce a 16M global or
-     // something.
-     if (NElements->getZExtValue() * DL->getTypeAllocSize(AllocTy) < 2048) {
--      GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, DL, TLI);
-+      GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy,
-+                                          NElements, DL, TLI)->getIterator();
-       return true;
-     }
- 
-@@ -1551,7 +1555,7 @@
-     }
- 
-     GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, DL, TLI, true),
--                               DL, TLI);
-+                               DL, TLI)->getIterator();
-     return true;
-   }
- 
-@@ -1626,7 +1630,7 @@
-                                              GV->getName()+".b",
-                                              GV->getThreadLocalMode(),
-                                              GV->getType()->getAddressSpace());
--  GV->getParent()->getGlobalList().insert(GV, NewGV);
-+  GV->getParent()->getGlobalList().insert(GV->getIterator(), NewGV);
- 
-   Constant *InitVal = GV->getInitializer();
-   assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
-@@ -1807,7 +1811,7 @@
-     if (DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>()) {
-       const DataLayout &DL = DLP->getDataLayout();
-       if (GlobalVariable *FirstNewGV = SRAGlobal(GV, DL)) {
--        GVI = FirstNewGV;  // Don't skip the newly produced globals!
-+        GVI = FirstNewGV->getIterator();  // Don't skip the newly produced globals!
-         return true;
-       }
-     }
-@@ -1830,7 +1834,7 @@
-           GV->eraseFromParent();
-           ++NumDeleted;
-         } else {
--          GVI = GV;
-+          GVI = GV->getIterator();
-         }
-         ++NumSubstitute;
-         return true;
-@@ -1905,7 +1909,7 @@
-   bool Changed = false;
-   // Optimize functions.
-   for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
--    Function *F = FI++;
-+    Function *F = &*FI++;
-     // Functions without names cannot be referenced outside this module.
-     if (!F->hasName() && !F->isDeclaration() && !F->hasLocalLinkage())
-       F->setLinkage(GlobalValue::InternalLinkage);
-@@ -1947,7 +1951,7 @@
- 
-   for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
-        GVI != E; ) {
--    GlobalVariable *GV = GVI++;
-+    GlobalVariable *GV = &*GVI++;
-     // Global variables without names cannot be referenced outside this module.
-     if (!GV->hasName() && !GV->isDeclaration() && !GV->hasLocalLinkage())
-       GV->setLinkage(GlobalValue::InternalLinkage);
-@@ -2446,7 +2450,7 @@
-       InstResult = AllocaTmps.back().get();
-       DEBUG(dbgs() << "Found an alloca. Result: " << *InstResult << "\n");
-     } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
--      CallSite CS(CurInst);
-+      CallSite CS(&*CurInst);
- 
-       // Debug info can safely be ignored here.
-       if (isa<DbgInfoIntrinsic>(CS.getInstruction())) {
-@@ -2608,7 +2612,7 @@
-       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
-         InstResult = ConstantFoldConstantExpression(CE, DL, TLI);
- 
--      setVal(CurInst, InstResult);
-+      setVal(&*CurInst, InstResult);
-     }
- 
-     // If we just processed an invoke, we finished evaluating the block.
-@@ -2639,7 +2643,7 @@
-   unsigned ArgNo = 0;
-   for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
-        ++AI, ++ArgNo)
--    setVal(AI, ActualArgs[ArgNo]);
-+    setVal(&*AI, ActualArgs[ArgNo]);
- 
-   // ExecutedBlocks - We only handle non-looping, non-recursive code.  As such,
-   // we can only evaluate any one basic block at most once.  This set keeps
-@@ -2647,7 +2651,7 @@
-   SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
- 
-   // CurBB - The current basic block we're evaluating.
--  BasicBlock *CurBB = F->begin();
-+  BasicBlock *CurBB = &F->front();
- 
-   BasicBlock::iterator CurInst = CurBB->begin();
- 
-@@ -2897,15 +2901,15 @@
- 
-     if (RenameTarget) {
-       // Give the aliasee the name, linkage and other attributes of the alias.
--      Target->takeName(J);
-+      Target->takeName(&*J);
-       Target->setLinkage(J->getLinkage());
-       Target->setVisibility(J->getVisibility());
-       Target->setDLLStorageClass(J->getDLLStorageClass());
- 
--      if (Used.usedErase(J))
-+      if (Used.usedErase(&*J))
-         Used.usedInsert(Target);
- 
--      if (Used.compilerUsedErase(J))
-+      if (Used.compilerUsedErase(&*J))
-         Used.compilerUsedInsert(Target);
-     } else if (mayHaveOtherReferences(*J, Used))
-       continue;
---- lib/Transforms/IPO/Internalize.cpp	2014-08-24 16:23:06.000000000 -0700
-+++ lib/Transforms/IPO/Internalize.cpp	2015-11-29 19:22:14.785278600 -0800
-@@ -162,7 +162,7 @@
- 
-     if (ExternalNode)
-       // Remove a callgraph edge from the external node to this function.
--      ExternalNode->removeOneAbstractEdgeTo((*CG)[I]);
-+      ExternalNode->removeOneAbstractEdgeTo((*CG)[&*I]);
- 
-     Changed = true;
-     ++NumFunctions;
---- lib/Transforms/IPO/LoopExtractor.cpp	2014-07-21 10:06:51.000000000 -0700
-+++ lib/Transforms/IPO/LoopExtractor.cpp	2015-11-29 19:23:56.327652268 -0800
-@@ -259,7 +259,7 @@
-     // Figure out which index the basic block is in its function.
-     Function::iterator BBI = MF->begin();
-     std::advance(BBI, std::distance(F->begin(), Function::iterator(BB)));
--    TranslatedBlocksToNotExtract.insert(BBI);
-+    TranslatedBlocksToNotExtract.insert(&*BBI);
-   }
- 
-   while (!BlocksToNotExtractByName.empty()) {
-@@ -278,7 +278,7 @@
-         BasicBlock &BB = *BI;
-         if (BB.getName() != BlockName) continue;
- 
--        TranslatedBlocksToNotExtract.insert(BI);
-+        TranslatedBlocksToNotExtract.insert(&*BI);
-       }
-     }
- 
-@@ -291,8 +291,8 @@
-   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
-     SplitLandingPadPreds(&*F);
-     for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
--      if (!TranslatedBlocksToNotExtract.count(BB))
--        BlocksToExtract.push_back(BB);
-+      if (!TranslatedBlocksToNotExtract.count(&*BB))
-+        BlocksToExtract.push_back(&*BB);
-   }
- 
-   for (unsigned i = 0, e = BlocksToExtract.size(); i != e; ++i) {
---- lib/Transforms/IPO/MergeFunctions.cpp	2014-11-18 23:49:26.000000000 -0800
-+++ lib/Transforms/IPO/MergeFunctions.cpp	2015-11-29 19:32:19.065098905 -0800
-@@ -929,7 +929,7 @@
-   BasicBlock::const_iterator InstR = BBR->begin(), InstRE = BBR->end();
- 
-   do {
--    if (int Res = cmpValues(InstL, InstR))
-+    if (int Res = cmpValues(&*InstL, &*InstR))
-       return Res;
- 
-     const GetElementPtrInst *GEPL = dyn_cast<GetElementPtrInst>(InstL);
-@@ -947,7 +947,7 @@
-       if (int Res = cmpGEPs(GEPL, GEPR))
-         return Res;
-     } else {
--      if (int Res = cmpOperations(InstL, InstR))
-+      if (int Res = cmpOperations(&*InstL, &*InstR))
-         return Res;
-       assert(InstL->getNumOperands() == InstR->getNumOperands());
- 
-@@ -1019,7 +1019,7 @@
-                                     ArgRI = FnR->arg_begin(),
-                                     ArgLE = FnL->arg_end();
-        ArgLI != ArgLE; ++ArgLI, ++ArgRI) {
--    if (cmpValues(ArgLI, ArgRI) != 0)
-+    if (cmpValues(&*ArgLI, &*ArgRI) != 0)
-       llvm_unreachable("Arguments repeat!");
-   }
- 
-@@ -1217,7 +1217,7 @@
- 
-   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
-     if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage())
--      Deferred.push_back(WeakVH(I));
-+      Deferred.push_back(WeakVH(&*I));
-   }
- 
-   do {
-@@ -1342,7 +1342,7 @@
-   FunctionType *FFTy = F->getFunctionType();
-   for (Function::arg_iterator AI = NewG->arg_begin(), AE = NewG->arg_end();
-        AI != AE; ++AI) {
--    Args.push_back(createCast(Builder, (Value*)AI, FFTy->getParamType(i)));
-+    Args.push_back(createCast(Builder, &*AI, FFTy->getParamType(i)));
-     ++i;
-   }
- 
---- lib/Transforms/IPO/PartialInlining.cpp	2014-07-21 10:06:51.000000000 -0700
-+++ lib/Transforms/IPO/PartialInlining.cpp	2015-11-30 05:52:13.004988742 -0800
-@@ -50,7 +50,7 @@
- 
- Function* PartialInliner::unswitchFunction(Function* F) {
-   // First, verify that this function is an unswitching candidate...
--  BasicBlock* entryBlock = F->begin();
-+  BasicBlock* entryBlock = &F->front();
-   BranchInst *BR = dyn_cast<BranchInst>(entryBlock->getTerminator());
-   if (!BR || BR->isUnconditional())
-     return nullptr;
-@@ -88,10 +88,10 @@
-   // sequence of PHIs, some of which will go in the extracted region, and some
-   // of which will go outside.
-   BasicBlock* preReturn = newReturnBlock;
--  newReturnBlock = newReturnBlock->splitBasicBlock(
--                                              newReturnBlock->getFirstNonPHI());
-+  newReturnBlock =
-+    newReturnBlock->splitBasicBlock(newReturnBlock->getFirstNonPHI()->getIterator());
-   BasicBlock::iterator I = preReturn->begin();
--  BasicBlock::iterator Ins = newReturnBlock->begin();
-+  Instruction *Ins = &newReturnBlock->front();
-   while (I != preReturn->end()) {
-     PHINode* OldPhi = dyn_cast<PHINode>(I);
-     if (!OldPhi) break;
-@@ -100,7 +100,7 @@
-     OldPhi->replaceAllUsesWith(retPhi);
-     Ins = newReturnBlock->getFirstNonPHI();
-     
--    retPhi->addIncoming(I, preReturn);
-+    retPhi->addIncoming(&*I, preReturn);
-     retPhi->addIncoming(OldPhi->getIncomingValueForBlock(newEntryBlock),
-                         newEntryBlock);
-     OldPhi->removeIncomingValue(newEntryBlock);
-@@ -116,7 +116,7 @@
-        FE = duplicateFunction->end(); FI != FE; ++FI)
-     if (&*FI != newEntryBlock && &*FI != newReturnBlock &&
-         &*FI != newNonReturnBlock)
--      toExtract.push_back(FI);
-+      toExtract.push_back(&*FI);
-       
-   // The CodeExtractor needs a dominator tree.
-   DominatorTree DT;
---- lib/Transforms/IPO/PruneEH.cpp	2015-01-12 19:46:47.000000000 -0800
-+++ lib/Transforms/IPO/PruneEH.cpp	2015-11-30 05:53:43.868963013 -0800
-@@ -218,7 +218,7 @@
- 
-           // Remove the uncond branch and add an unreachable.
-           BB->getInstList().pop_back();
--          new UnreachableInst(BB->getContext(), BB);
-+          new UnreachableInst(BB->getContext(), &*BB);
- 
-           DeleteBasicBlock(New);  // Delete the new BB.
-           MadeChange = true;
---- lib/Transforms/IPO/StripDeadPrototypes.cpp	2014-04-21 19:55:47.000000000 -0700
-+++ lib/Transforms/IPO/StripDeadPrototypes.cpp	2015-11-30 05:54:57.769272028 -0800
-@@ -47,7 +47,9 @@
-   
-   // Erase dead function prototypes.
-   for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
--    Function *F = I++;
-+    Function *F = &*I;
-+    ++I;
-+
-     // Function must be a prototype and unused.
-     if (F->isDeclaration() && F->use_empty()) {
-       F->eraseFromParent();
-@@ -59,7 +61,9 @@
-   // Erase dead global var prototypes.
-   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
-        I != E; ) {
--    GlobalVariable *GV = I++;
-+    GlobalVariable *GV = &*I;
-+    ++I;
-+
-     // Global must be a prototype and unused.
-     if (GV->isDeclaration() && GV->use_empty())
-       GV->eraseFromParent();
---- lib/Transforms/IPO/StripSymbols.cpp	2014-12-09 10:38:53.000000000 -0800
-+++ lib/Transforms/IPO/StripSymbols.cpp	2015-11-30 06:01:52.193630900 -0800
-@@ -211,13 +211,13 @@
- 
-   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
-        I != E; ++I) {
--    if (I->hasLocalLinkage() && llvmUsedValues.count(I) == 0)
-+    if (I->hasLocalLinkage() && llvmUsedValues.count(&*I) == 0)
-       if (!PreserveDbgInfo || !I->getName().startswith("llvm.dbg"))
-         I->setName("");     // Internal symbols can't participate in linkage
-   }
- 
-   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
--    if (I->hasLocalLinkage() && llvmUsedValues.count(I) == 0)
-+    if (I->hasLocalLinkage() && llvmUsedValues.count(&*I) == 0)
-       if (!PreserveDbgInfo || !I->getName().startswith("llvm.dbg"))
-         I->setName("");     // Internal symbols can't participate in linkage
-     StripSymtab(I->getValueSymbolTable(), PreserveDbgInfo);
---- lib/Transforms/InstCombine/InstCombineCalls.cpp	2015-01-22 11:40:47.000000000 -0800
-+++ lib/Transforms/InstCombine/InstCombineCalls.cpp	2015-11-30 06:53:40.815329138 -0800
-@@ -1010,15 +1010,14 @@
-     // happen when variable allocas are DCE'd.
-     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
-       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
--        BasicBlock::iterator BI = SS;
--        if (&*++BI == II)
-+        if (&*++SS->getIterator() == II)
-           return EraseInstFromFunction(CI);
-       }
-     }
- 
-     // Scan down this block to see if there is another stack restore in the
-     // same block without an intervening call/alloca.
--    BasicBlock::iterator BI = II;
-+    BasicBlock::iterator BI(II);
-     TerminatorInst *TI = II->getParent()->getTerminator();
-     bool CannotRemove = false;
-     for (++BI; &*BI != TI; ++BI) {
-@@ -1235,9 +1234,9 @@
-                                                Value *TrampMem) {
-   // Visit all the previous instructions in the basic block, and try to find a
-   // init.trampoline which has a direct path to the adjust.trampoline.
--  for (BasicBlock::iterator I = AdjustTramp,
-+  for (BasicBlock::iterator I = AdjustTramp->getIterator(),
-        E = AdjustTramp->getParent()->begin(); I != E; ) {
--    Instruction *Inst = --I;
-+    Instruction *Inst = &*--I;
-     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
-       if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
-           II->getOperand(0) == TrampMem)
---- lib/Transforms/InstCombine/InstCombineCasts.cpp	2014-12-12 10:48:37.000000000 -0800
-+++ lib/Transforms/InstCombine/InstCombineCasts.cpp	2015-11-30 07:19:19.812837233 -0800
-@@ -86,7 +86,7 @@
-   PointerType *PTy = cast<PointerType>(CI.getType());
- 
-   BuilderTy AllocaBuilder(*Builder);
--  AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
-+  AllocaBuilder.SetInsertPoint(&AI);
- 
-   // Get the type really allocated and the type casted to.
-   Type *AllocElTy = AI.getAllocatedType();
---- lib/Transforms/InstCombine/InstCombineLoadStoreAlloca.cpp	2015-02-12 19:19:15.000000000 -0800
-+++ lib/Transforms/InstCombine/InstCombineLoadStoreAlloca.cpp	2015-11-30 07:27:36.109476800 -0800
-@@ -187,8 +187,9 @@
-       // Scan to the end of the allocation instructions, to skip over a block of
-       // allocas if possible...also skip interleaved debug info
-       //
--      BasicBlock::iterator It = New;
--      while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
-+      BasicBlock::iterator It(New);
-+      while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It))
-+        ++It;
- 
-       // Now that I is pointing to the first non-allocation-inst in the block,
-       // insert our getelementptr instruction...
-@@ -419,7 +420,7 @@
-   // Do really simple store-to-load forwarding and load CSE, to catch cases
-   // where there are several consecutive memory accesses to the same location,
-   // separated by a few arithmetic operations.
--  BasicBlock::iterator BBI = &LI;
-+  BasicBlock::iterator BBI(LI);
-   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
-     return ReplaceInstUsesWith(
-         LI, Builder->CreateBitOrPointerCast(AvailableVal, LI.getType(),
-@@ -644,7 +645,7 @@
-   // Do really simple DSE, to catch cases where there are several consecutive
-   // stores to the same location, separated by a few arithmetic operations. This
-   // situation often occurs with bitfield accesses.
--  BasicBlock::iterator BBI = &SI;
-+  BasicBlock::iterator BBI(SI);
-   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
-        --ScanInsts) {
-     --BBI;
-@@ -703,7 +704,7 @@
-   // If this store is the last instruction in the basic block (possibly
-   // excepting debug info instructions), and if the block ends with an
-   // unconditional branch, try to move it to the successor block.
--  BBI = &SI;
-+  BBI = SI.getIterator();
-   do {
-     ++BBI;
-   } while (isa<DbgInfoIntrinsic>(BBI) ||
-@@ -759,7 +760,7 @@
-     return false;
- 
-   // Verify that the other block ends in a branch and is not otherwise empty.
--  BasicBlock::iterator BBI = OtherBB->getTerminator();
-+  BasicBlock::iterator BBI(OtherBB->getTerminator());
-   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
-   if (!OtherBr || BBI == OtherBB->begin())
-     return false;
---- lib/Transforms/InstCombine/InstCombineMulDivRem.cpp	2015-01-04 04:03:27.000000000 -0800
-+++ lib/Transforms/InstCombine/InstCombineMulDivRem.cpp	2015-11-30 07:30:31.455813053 -0800
-@@ -736,7 +736,7 @@
-     return true;
- 
-   // Scan the current block backward, looking for other uses of SI.
--  BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
-+  BasicBlock::iterator BBI = I.getIterator(), BBFront = I.getParent()->begin();
- 
-   while (BBI != BBFront) {
-     --BBI;
-@@ -750,10 +750,10 @@
-          I != E; ++I) {
-       if (*I == SI) {
-         *I = SI->getOperand(NonNullOperand);
--        Worklist.Add(BBI);
-+        Worklist.Add(&*BBI);
-       } else if (*I == SelectCond) {
-         *I = Builder->getInt1(NonNullOperand == 1);
--        Worklist.Add(BBI);
-+        Worklist.Add(&*BBI);
-       }
-     }
- 
---- lib/Transforms/InstCombine/InstCombinePHI.cpp	2015-01-04 04:03:27.000000000 -0800
-+++ lib/Transforms/InstCombine/InstCombinePHI.cpp	2015-11-30 07:32:38.250246960 -0800
-@@ -247,7 +247,7 @@
- /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
- /// to a register.
- static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
--  BasicBlock::iterator BBI = L, E = L->getParent()->end();
-+  BasicBlock::iterator BBI = L->getIterator(), E = L->getParent()->end();
- 
-   for (++BBI; BBI != E; ++BBI)
-     if (BBI->mayWriteToMemory())
-@@ -744,7 +744,7 @@
-         }
- 
-         // Otherwise, do an extract in the predecessor.
--        Builder->SetInsertPoint(Pred, Pred->getTerminator());
-+        Builder->SetInsertPoint(Pred->getTerminator());
-         Value *Res = InVal;
-         if (Offset)
-           Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
---- lib/Transforms/InstCombine/InstCombineVectorOps.cpp	2014-07-07 15:13:58.000000000 -0700
-+++ lib/Transforms/InstCombine/InstCombineVectorOps.cpp	2015-11-30 07:47:54.223248158 -0800
-@@ -162,8 +162,7 @@
-       Instruction *pos = dyn_cast<Instruction>(PHIInVal);
-       BasicBlock::iterator InsertPos;
-       if (pos && !isa<PHINode>(pos)) {
--        InsertPos = pos;
--        ++InsertPos;
-+        InsertPos = ++pos->getIterator();
-       } else {
-         InsertPos = inBB->getFirstInsertionPt();
-       }
---- lib/Transforms/InstCombine/InstCombine.h	2015-01-06 16:39:50.000000000 -0800
-+++ lib/Transforms/InstCombine/InstCombine.h	2015-11-30 06:47:44.140493020 -0800
-@@ -297,7 +297,7 @@
-     assert(New && !New->getParent() &&
-            "New instruction already inserted into a basic block!");
-     BasicBlock *BB = Old.getParent();
--    BB->getInstList().insert(&Old, New); // Insert inst
-+    BB->getInstList().insert(Old.getIterator(), New); // Insert inst
-     Worklist.Add(New);
-     return New;
-   }
---- lib/Transforms/InstCombine/InstructionCombining.cpp	2015-01-04 04:03:27.000000000 -0800
-+++ lib/Transforms/InstCombine/InstructionCombining.cpp	2015-11-30 09:32:37.959104590 -0800
-@@ -1417,13 +1417,13 @@
-     if (DI == -1) {
-       // All the GEPs feeding the PHI are identical. Clone one down into our
-       // BB so that it can be merged with the current GEP.
--      GEP.getParent()->getInstList().insert(GEP.getParent()->getFirstNonPHI(),
--                                            NewGEP);
-+      GEP.getParent()->getInstList().insert(
-+        GEP.getParent()->getFirstNonPHI()->getIterator(), NewGEP);
-     } else {
-       // All the GEPs feeding the PHI differ at a single offset. Clone a GEP
-       // into the current block so it can be merged, and create a new PHI to
-       // set that index.
--      Instruction *InsertPt = Builder->GetInsertPoint();
-+      Instruction *InsertPt = &*Builder->GetInsertPoint();
-       Builder->SetInsertPoint(PN);
-       PHINode *NewPN = Builder->CreatePHI(Op1->getOperand(DI)->getType(),
-                                           PN->getNumOperands());
-@@ -1434,8 +1434,8 @@
-                            PN->getIncomingBlock(I));
- 
-       NewGEP->setOperand(DI, NewPN);
--      GEP.getParent()->getInstList().insert(GEP.getParent()->getFirstNonPHI(),
--                                            NewGEP);
-+      GEP.getParent()->getInstList().insert(
-+        GEP.getParent()->getFirstNonPHI()->getIterator(), NewGEP);
-       NewGEP->setOperand(DI, NewPN);
-     }
- 
-@@ -1768,7 +1768,7 @@
-           if (Instruction *I = visitBitCast(*BCI)) {
-             if (I != BCI) {
-               I->takeName(BCI);
--              BCI->getParent()->getInstList().insert(BCI, I);
-+              BCI->getParent()->getInstList().insert(BCI->getIterator(), I);
-               ReplaceInstUsesWith(*BCI, I);
-             }
-             return &GEP;
-@@ -2269,7 +2269,7 @@
- 
-       // We need to insert these at the location of the old load, not at that of
-       // the extractvalue.
--      Builder->SetInsertPoint(L->getParent(), L);
-+      Builder->SetInsertPoint(L);
-       Value *GEP = Builder->CreateInBoundsGEP(L->getPointerOperand(), Indices);
-       // Returning the load directly will cause the main loop to insert it in
-       // the wrong spot, so use ReplaceInstUsesWith().
-@@ -2648,14 +2648,14 @@
-   // We can only sink load instructions if there is nothing between the load and
-   // the end of block that could change the value.
-   if (I->mayReadFromMemory()) {
--    for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
--         Scan != E; ++Scan)
-+    for (BasicBlock::iterator Scan = I->getIterator(),
-+         E = I->getParent()->end(); Scan != E; ++Scan)
-       if (Scan->mayWriteToMemory())
-         return false;
-   }
- 
-   BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
--  I->moveBefore(InsertPos);
-+  I->moveBefore(&*InsertPos);
-   ++NumSunkInst;
-   return true;
- }
-@@ -2690,7 +2690,8 @@
-       continue;
- 
-     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
--      Instruction *Inst = BBI++;
-+      Instruction *Inst = &*BBI;
-+      ++BBI;
- 
-       // DCE instruction if trivially dead.
-       if (isInstructionTriviallyDead(Inst, TLI)) {
-@@ -2787,22 +2788,21 @@
-     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
-     // track of which blocks we visit.
-     SmallPtrSet<BasicBlock*, 64> Visited;
--    MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, DL,
-+    MadeIRChange |= AddReachableCodeToWorklist(&F.front(), Visited, *this, DL,
-                                                TLI);
- 
-     // Do a quick scan over the function.  If we find any blocks that are
-     // unreachable, remove any instructions inside of them.  This prevents
-     // the instcombine code from having to deal with some bad special cases.
-     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
--      if (Visited.count(BB)) continue;
-+      if (Visited.count(&*BB)) continue;
- 
-       // Delete the instructions backwards, as it has a reduced likelihood of
-       // having to update as many def-use and use-def chains.
-       Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
-       while (EndInst != BB->begin()) {
-         // Delete the next to last instruction.
--        BasicBlock::iterator I = EndInst;
--        Instruction *Inst = --I;
-+        Instruction *Inst = &*--EndInst->getIterator();
-         if (!Inst->use_empty())
-           Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
-         if (isa<LandingPadInst>(Inst)) {
-@@ -2884,7 +2884,7 @@
-     }
- 
-     // Now that we have an instruction, try combining it to simplify it.
--    Builder->SetInsertPoint(I->getParent(), I);
-+    Builder->SetInsertPoint(I);
-     Builder->SetCurrentDebugLocation(I->getDebugLoc());
- 
- #ifndef NDEBUG
-@@ -2914,7 +2914,7 @@
- 
-         // Insert the new instruction into the basic block...
-         BasicBlock *InstParent = I->getParent();
--        BasicBlock::iterator InsertPos = I;
-+        BasicBlock::iterator InsertPos = I->getIterator();
- 
-         // If we replace a PHI with something that isn't a PHI, fix up the
-         // insertion point.
---- lib/Transforms/Instrumentation/AddressSanitizer.cpp	2015-02-03 10:58:33.000000000 -0800
-+++ lib/Transforms/Instrumentation/AddressSanitizer.cpp	2016-01-23 20:36:01.000000000 -0800
-@@ -158,10 +158,11 @@
-                 "this number of memory accesses, use callbacks instead of "
-                 "inline checks (-1 means never use callbacks)."),
-        cl::Hidden, cl::init(7000));
-+static std::string AsanInitString("__asan_");
- static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
-        "asan-memory-access-callback-prefix",
-        cl::desc("Prefix for memory access callbacks"), cl::Hidden,
--       cl::init("__asan_"));
-+       cl::init(AsanInitString));
- static cl::opt<bool> ClInstrumentAllocas("asan-instrument-allocas",
-        cl::desc("instrument dynamic allocas"), cl::Hidden, cl::init(false));
- 
-@@ -1007,7 +1008,8 @@
- void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
-                                                   GlobalValue *ModuleName) {
-   // Set up the arguments to our poison/unpoison functions.
--  IRBuilder<> IRB(GlobalInit.begin()->getFirstInsertionPt());
-+  IRBuilder<> IRB(&GlobalInit.front(),
-+                  GlobalInit.front().getFirstInsertionPt());
- 
-   // Add a call to poison all external globals before the given function starts.
-   Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
-@@ -1402,7 +1404,7 @@
-   // We cannot just ignore these methods, because they may call other
-   // instrumented functions.
-   if (F.getName().find(" load]") != std::string::npos) {
--    IRBuilder<> IRB(F.begin()->begin());
-+    IRBuilder<> IRB(&F.front(), F.front().begin());
-     IRB.CreateCall(AsanInitFunction);
-     return true;
-   }
---- lib/Transforms/Instrumentation/BoundsChecking.cpp	2014-04-24 22:29:35.000000000 -0700
-+++ lib/Transforms/Instrumentation/BoundsChecking.cpp	2015-11-30 11:29:13.966151410 -0800
-@@ -108,7 +108,7 @@
-   }
-   ++ChecksAdded;
- 
--  Instruction *Inst = Builder->GetInsertPoint();
-+  BasicBlock::iterator Inst = Builder->GetInsertPoint();
-   BasicBlock *OldBB = Inst->getParent();
-   BasicBlock *Cont = OldBB->splitBasicBlock(Inst);
-   OldBB->getTerminator()->eraseFromParent();
---- lib/Transforms/Instrumentation/DataFlowSanitizer.cpp	2014-12-05 13:22:32.000000000 -0800
-+++ lib/Transforms/Instrumentation/DataFlowSanitizer.cpp	2015-11-30 13:39:14.566562460 -0800
-@@ -580,7 +580,7 @@
-     DFSanFunction DFSF(*this, F, /*IsNativeABI=*/true);
-     Function::arg_iterator ValAI = F->arg_begin(), ShadowAI = AI; ++ValAI;
-     for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++ShadowAI, --N)
--      DFSF.ValShadowMap[ValAI] = ShadowAI;
-+      DFSF.ValShadowMap[&*ValAI] = &*ShadowAI;
-     DFSanVisitor(DFSF).visitCallInst(*CI);
-     if (!FT->getReturnType()->isVoidTy())
-       new StoreInst(DFSF.getShadow(RI->getReturnValue()),
-@@ -648,16 +648,16 @@
- 
-   std::vector<Function *> FnsToInstrument;
-   llvm::SmallPtrSet<Function *, 2> FnsWithNativeABI;
--  for (Module::iterator i = M.begin(), e = M.end(); i != e; ++i) {
--    if (!i->isIntrinsic() &&
--        i != DFSanUnionFn &&
--        i != DFSanCheckedUnionFn &&
--        i != DFSanUnionLoadFn &&
--        i != DFSanUnimplementedFn &&
--        i != DFSanSetLabelFn &&
--        i != DFSanNonzeroLabelFn &&
--        i != DFSanVarargWrapperFn)
--      FnsToInstrument.push_back(&*i);
-+  for (Function &i : M) {
-+    if (!i.isIntrinsic() &&
-+        &i != DFSanUnionFn &&
-+        &i != DFSanCheckedUnionFn &&
-+        &i != DFSanUnionLoadFn &&
-+        &i != DFSanUnimplementedFn &&
-+        &i != DFSanSetLabelFn &&
-+        &i != DFSanNonzeroLabelFn &&
-+        &i != DFSanVarargWrapperFn)
-+      FnsToInstrument.push_back(&i);
-   }
- 
-   // Give function aliases prefixes when necessary, and build wrappers where the
-@@ -715,7 +715,7 @@
-                                     NewFArg = NewF->arg_begin(),
-                                     FArgEnd = F.arg_end();
-              FArg != FArgEnd; ++FArg, ++NewFArg) {
--          FArg->replaceAllUsesWith(NewFArg);
-+          FArg->replaceAllUsesWith(&*NewFArg);
-         }
-         NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
- 
-@@ -847,7 +847,7 @@
-         if (Instruction *I = dyn_cast<Instruction>(V))
-           Pos = I->getNextNode();
-         else
--          Pos = DFSF.F->getEntryBlock().begin();
-+          Pos = &DFSF.F->getEntryBlock().front();
-         while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
-           Pos = Pos->getNextNode();
-         IRBuilder<> IRB(Pos);
-@@ -869,7 +869,7 @@
-   if (DFS.ArgTLS)
-     return ArgTLSPtr = DFS.ArgTLS;
- 
--  IRBuilder<> IRB(F->getEntryBlock().begin());
-+  IRBuilder<> IRB(&F->getEntryBlock().front());
-   return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLS);
- }
- 
-@@ -879,7 +879,7 @@
-   if (DFS.RetvalTLS)
-     return RetvalTLSPtr = DFS.RetvalTLS;
- 
--  IRBuilder<> IRB(F->getEntryBlock().begin());
-+  IRBuilder<> IRB(&F->getEntryBlock().front());
-   return RetvalTLSPtr = IRB.CreateCall(DFS.GetRetvalTLS);
- }
- 
-@@ -911,7 +911,7 @@
-         Function::arg_iterator i = F->arg_begin();
-         while (ArgIdx--)
-           ++i;
--        Shadow = i;
-+        Shadow = &*i;
-         assert(Shadow->getType() == DFS.ShadowTy);
-         break;
-       }
-@@ -996,7 +996,7 @@
-     Call->addAttribute(2, Attribute::ZExt);
- 
-     BasicBlock *Tail = BI->getSuccessor(0);
--    PHINode *Phi = PHINode::Create(DFS.ShadowTy, 2, "", Tail->begin());
-+    PHINode *Phi = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
-     Phi->addIncoming(Call, Call->getParent());
-     Phi->addIncoming(V1, Head);
- 
-@@ -1109,7 +1109,7 @@
-     Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
- 
-     BasicBlock *Head = Pos->getParent();
--    BasicBlock *Tail = Head->splitBasicBlock(Pos);
-+    BasicBlock *Tail = Head->splitBasicBlock(Pos->getIterator());
- 
-     if (DomTreeNode *OldNode = DT.getNode(Head)) {
-       std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
-@@ -1476,7 +1476,7 @@
-           auto LabelVAAlloca =
-               new AllocaInst(ArrayType::get(DFSF.DFS.ShadowTy,
-                                             CS.arg_size() - FT->getNumParams()),
--                             "labelva", DFSF.F->getEntryBlock().begin());
-+                             "labelva", &DFSF.F->getEntryBlock().front());
- 
-           for (unsigned n = 0; i != CS.arg_end(); ++i, ++n) {
-             auto LabelVAPtr = IRB.CreateStructGEP(LabelVAAlloca, n);
-@@ -1490,7 +1490,7 @@
-           if (!DFSF.LabelReturnAlloca) {
-             DFSF.LabelReturnAlloca =
-                 new AllocaInst(DFSF.DFS.ShadowTy, "labelreturn",
--                               DFSF.F->getEntryBlock().begin());
-+                               &DFSF.F->getEntryBlock().front());
-           }
-           Args.push_back(DFSF.LabelReturnAlloca);
-         }
-@@ -1529,11 +1529,11 @@
-   if (!CS.getType()->isVoidTy()) {
-     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
-       if (II->getNormalDest()->getSinglePredecessor()) {
--        Next = II->getNormalDest()->begin();
-+        Next = &II->getNormalDest()->front();
-       } else {
-         BasicBlock *NewBB =
-             SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DFS);
--        Next = NewBB->begin();
-+        Next = &NewBB->front();
-       }
-     } else {
-       Next = CS->getNextNode();
-@@ -1568,7 +1568,7 @@
-       unsigned VarArgSize = CS.arg_size() - FT->getNumParams();
-       ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize);
-       AllocaInst *VarArgShadow =
--          new AllocaInst(VarArgArrayTy, "", DFSF.F->getEntryBlock().begin());
-+          new AllocaInst(VarArgArrayTy, "", &DFSF.F->getEntryBlock().front());
-       Args.push_back(IRB.CreateConstGEP2_32(VarArgShadow, 0, 0));
-       for (unsigned n = 0; i != e; ++i, ++n) {
-         IRB.CreateStore(DFSF.getShadow(*i),
---- lib/Transforms/Instrumentation/GCOVProfiling.cpp	2015-05-04 12:18:18.000000000 -0700
-+++ lib/Transforms/Instrumentation/GCOVProfiling.cpp	2016-01-23 20:38:11.000000000 -0800
-@@ -44,8 +44,10 @@
- 
- #define DEBUG_TYPE "insert-gcov-profiling"
- 
-+static std::string VersionInitString("402*");
- static cl::opt<std::string>
--DefaultGCOVVersion("default-gcov-version", cl::init("402*"), cl::Hidden,
-+DefaultGCOVVersion("default-gcov-version",
-+                   cl::init(VersionInitString), cl::Hidden,
-                    cl::ValueRequired);
- static cl::opt<bool> DefaultExitBlockBeforeBody("gcov-exit-block-before-body",
-                                                 cl::init(false), cl::Hidden);
-@@ -351,8 +353,8 @@
-       std::string EdgeDestinations;
-       raw_string_ostream EDOS(EdgeDestinations);
-       Function *F = Blocks.begin()->first->getParent();
--      for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
--        GCOVBlock &Block = getBlock(I);
-+      for (BasicBlock &I : *F) {
-+        GCOVBlock &Block = getBlock(&I);
-         for (int i = 0, e = Block.OutEdges.size(); i != e; ++i)
-           EDOS << Block.OutEdges[i]->Number;
-       }
-@@ -393,8 +395,8 @@
-       // Emit edges between blocks.
-       if (Blocks.empty()) return;
-       Function *F = Blocks.begin()->first->getParent();
--      for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
--        GCOVBlock &Block = getBlock(I);
-+      for (BasicBlock &I : *F) {
-+        GCOVBlock &Block = getBlock(&I);
-         if (Block.OutEdges.empty()) continue;
- 
-         writeBytes(EdgeTag, 4);
-@@ -409,8 +411,8 @@
-       }
- 
-       // Emit lines for each block.
--      for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
--        getBlock(I).writeOut();
-+      for (BasicBlock &I : *F) {
-+        getBlock(&I).writeOut();
-       }
-     }
- 
-@@ -522,7 +524,7 @@
-       GCOVFunction &Func = *Funcs.back();
- 
-       for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
--        GCOVBlock &Block = Func.getBlock(BB);
-+        GCOVBlock &Block = Func.getBlock(&*BB);
-         TerminatorInst *TI = BB->getTerminator();
-         if (int successors = TI->getNumSuccessors()) {
-           for (int i = 0; i != successors; ++i) {
-@@ -618,7 +620,7 @@
-         int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
-         if (Successors) {
-           if (Successors == 1) {
--            IRBuilder<> Builder(BB->getFirstInsertionPt());
-+            IRBuilder<> Builder(&*BB->getFirstInsertionPt());
-             Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
-                                                                 Edge);
-             Value *Count = Builder.CreateLoad(Counter);
-@@ -637,7 +639,7 @@
-             Count = Builder.CreateAdd(Count, Builder.getInt64(1));
-             Builder.CreateStore(Count, Counter);
-           } else {
--            ComplexEdgePreds.insert(BB);
-+            ComplexEdgePreds.insert(&*BB);
-             for (int i = 0; i != Successors; ++i)
-               ComplexEdgeSuccs.insert(TI->getSuccessor(i));
-           }
-@@ -653,13 +655,13 @@
-         GlobalVariable *EdgeState = getEdgeStateValue();
- 
-         for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
--          IRBuilder<> Builder(ComplexEdgePreds[i + 1]->getFirstInsertionPt());
-+          IRBuilder<> Builder(&*ComplexEdgePreds[i + 1]->getFirstInsertionPt());
-           Builder.CreateStore(Builder.getInt32(i), EdgeState);
-         }
- 
-         for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
-           // Call runtime to perform increment.
--          IRBuilder<> Builder(ComplexEdgeSuccs[i+1]->getFirstInsertionPt());
-+          IRBuilder<> Builder(&*ComplexEdgeSuccs[i + 1]->getFirstInsertionPt());
-           Value *CounterPtrArray =
-             Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
-                                                i * ComplexEdgePreds.size());
-@@ -743,8 +745,8 @@
-         IRBuilder<> Builder(Succ);
-         Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
-                                                             Edge + i);
--        EdgeTable[((Succs.idFor(Succ)-1) * Preds.size()) +
--                  (Preds.idFor(BB)-1)] = cast<Constant>(Counter);
-+        EdgeTable[((Succs.idFor(Succ) - 1) * Preds.size()) +
-+                  (Preds.idFor(&*BB) - 1)] = cast<Constant>(Counter);
-       }
-     }
-     Edge += Successors;
-@@ -913,7 +915,7 @@
- 
-   // uint32_t pred = *predecessor;
-   // if (pred == 0xffffffff) return;
--  Argument *Arg = Fn->arg_begin();
-+  Argument *Arg = &*Fn->arg_begin();
-   Arg->setName("predecessor");
-   Value *Pred = Builder.CreateLoad(Arg, "pred");
-   Value *Cond = Builder.CreateICmpEQ(Pred, Builder.getInt32(0xffffffff));
-@@ -924,7 +926,7 @@
-   // uint64_t *counter = counters[pred];
-   // if (!counter) return;
-   Value *ZExtPred = Builder.CreateZExt(Pred, Builder.getInt64Ty());
--  Arg = std::next(Fn->arg_begin());
-+  Arg = &*std::next(Fn->arg_begin());
-   Arg->setName("counters");
-   Value *GEP = Builder.CreateGEP(Arg, ZExtPred);
-   Value *Counter = Builder.CreateLoad(GEP, "counter");
---- lib/Transforms/Instrumentation/InstrProfiling.cpp	2015-02-10 20:41:09.000000000 -0800
-+++ lib/Transforms/Instrumentation/InstrProfiling.cpp	2015-11-30 19:51:07.408467787 -0800
-@@ -143,7 +143,7 @@
- void InstrProfiling::lowerIncrement(InstrProfIncrementInst *Inc) {
-   GlobalVariable *Counters = getOrCreateRegionCounters(Inc);
- 
--  IRBuilder<> Builder(Inc->getParent(), *Inc);
-+  IRBuilder<> Builder(Inc);
-   uint64_t Index = Inc->getIndex()->getZExtValue();
-   llvm::Value *Addr = Builder.CreateConstInBoundsGEP2_64(Counters, 0, Index);
-   llvm::Value *Count = Builder.CreateLoad(Addr, "pgocount");
---- lib/Transforms/Instrumentation/MemorySanitizer.cpp	2015-02-06 14:06:43.000000000 -0800
-+++ lib/Transforms/Instrumentation/MemorySanitizer.cpp	2015-11-30 19:55:19.370562015 -0800
-@@ -603,7 +603,7 @@
-         Value *Cmp = IRB.CreateICmpNE(
-             ConvertedShadow, getCleanShadow(ConvertedShadow), "_mscmp");
-         Instruction *CheckTerm = SplitBlockAndInsertIfThen(
--            Cmp, IRB.GetInsertPoint(), false, MS.OriginStoreWeights);
-+            Cmp, &*IRB.GetInsertPoint(), false, MS.OriginStoreWeights);
-         IRBuilder<> IRBNew(CheckTerm);
-         IRBNew.CreateAlignedStore(updateOrigin(Origin, IRBNew),
-                                   getOriginPtr(Addr, IRBNew, Alignment),
-@@ -2396,9 +2396,10 @@
-     // Until we have full dynamic coverage, make sure the retval shadow is 0.
-     Value *Base = getShadowPtrForRetval(&I, IRBBefore);
-     IRBBefore.CreateAlignedStore(getCleanShadow(&I), Base, kShadowTLSAlignment);
--    Instruction *NextInsn = nullptr;
-+    BasicBlock::iterator NextInsn;
-     if (CS.isCall()) {
--      NextInsn = I.getNextNode();
-+      NextInsn = ++I.getIterator();
-+      assert(NextInsn != I.getParent()->end());
-     } else {
-       BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
-       if (!NormalDest->getSinglePredecessor()) {
-@@ -2410,10 +2411,10 @@
-         return;
-       }
-       NextInsn = NormalDest->getFirstInsertionPt();
--      assert(NextInsn &&
-+      assert(NextInsn != NormalDest->end() &&
-              "Could not find insertion point for retval shadow load");
-     }
--    IRBuilder<> IRBAfter(NextInsn);
-+    IRBuilder<> IRBAfter(&*NextInsn);
-     Value *RetvalShadow =
-       IRBAfter.CreateAlignedLoad(getShadowPtrForRetval(&I, IRBAfter),
-                                  kShadowTLSAlignment, "_msret");
---- lib/Transforms/Instrumentation/SanitizerCoverage.cpp	2015-01-02 16:54:43.000000000 -0800
-+++ lib/Transforms/Instrumentation/SanitizerCoverage.cpp	2015-11-30 19:58:56.426390313 -0800
-@@ -275,7 +275,8 @@
-   bool IsEntryBB = &BB == &F.getEntryBlock();
-   DebugLoc EntryLoc =
-       IsEntryBB ? IP->getDebugLoc().getFnDebugLoc(*C) : IP->getDebugLoc();
--  IRBuilder<> IRB(IP);
-+
-+  IRBuilder<> IRB(&*IP);
-   IRB.SetCurrentDebugLocation(EntryLoc);
-   SmallVector<Value *, 1> Indices;
-   Value *GuardP = IRB.CreateAdd(
-@@ -290,7 +291,7 @@
-                     MDNode::get(*C, None));
-   Value *Cmp = IRB.CreateICmpSGE(Constant::getNullValue(Load->getType()), Load);
-   Instruction *Ins = SplitBlockAndInsertIfThen(
--      Cmp, IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
-+      Cmp, &*IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
-   IRB.SetInsertPoint(Ins);
-   IRB.SetCurrentDebugLocation(EntryLoc);
-   // __sanitizer_cov gets the PC of the instruction using GET_CALLER_PC.
-@@ -300,7 +301,7 @@
-   if (ClExperimentalTracing) {
-     // Experimental support for tracing.
-     // Insert a callback with the same guard variable as used for coverage.
--    IRB.SetInsertPoint(IP);
-+    IRB.SetInsertPoint(&*IP);
-     IRB.CreateCall(IsEntryBB ? SanCovTraceEnter : SanCovTraceBB, GuardP);
-   }
- }
---- lib/Transforms/ObjCARC/DependencyAnalysis.cpp	2014-11-18 23:49:26.000000000 -0800
-+++ lib/Transforms/ObjCARC/DependencyAnalysis.cpp	2015-11-30 20:05:22.864307715 -0800
-@@ -209,7 +209,7 @@
-                                 SmallPtrSetImpl<Instruction *> &DependingInsts,
-                                 SmallPtrSetImpl<const BasicBlock *> &Visited,
-                                 ProvenanceAnalysis &PA) {
--  BasicBlock::iterator StartPos = StartInst;
-+  BasicBlock::iterator StartPos = StartInst->getIterator();
- 
-   SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
-   Worklist.push_back(std::make_pair(StartBB, StartPos));
-@@ -235,7 +235,7 @@
-         break;
-       }
- 
--      Instruction *Inst = --LocalStartPos;
-+      Instruction *Inst = &*--LocalStartPos;
-       if (Depends(Flavor, Inst, Arg, PA)) {
-         DependingInsts.insert(Inst);
-         break;
---- lib/Transforms/ObjCARC/ObjCARCAPElim.cpp	2014-05-16 13:39:27.000000000 -0700
-+++ lib/Transforms/ObjCARC/ObjCARCAPElim.cpp	2015-11-30 20:09:20.487861680 -0800
-@@ -72,12 +72,9 @@
-   if (const Function *Callee = CS.getCalledFunction()) {
-     if (Callee->isDeclaration() || Callee->mayBeOverridden())
-       return true;
--    for (Function::const_iterator I = Callee->begin(), E = Callee->end();
--         I != E; ++I) {
--      const BasicBlock *BB = I;
--      for (BasicBlock::const_iterator J = BB->begin(), F = BB->end();
--           J != F; ++J)
--        if (ImmutableCallSite JCS = ImmutableCallSite(J))
-+    for (const BasicBlock &BB : *Callee) {
-+      for (const Instruction &I : BB)
-+        if (ImmutableCallSite JCS = ImmutableCallSite(&I))
-           // This recursion depth limit is arbitrary. It's just great
-           // enough to cover known interesting testcases.
-           if (Depth < 3 &&
-@@ -96,7 +93,7 @@
- 
-   Instruction *Push = nullptr;
-   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
--    Instruction *Inst = I++;
-+    Instruction *Inst = &*I++;
-     switch (GetBasicInstructionClass(Inst)) {
-     case IC_AutoreleasepoolPush:
-       Push = Inst;
-@@ -169,7 +166,7 @@
-     if (std::next(F->begin()) != F->end())
-       continue;
-     // Ok, a single-block constructor function definition. Try to optimize it.
--    Changed |= OptimizeBB(F->begin());
-+    Changed |= OptimizeBB(&F->front());
-   }
- 
-   return Changed;
---- lib/Transforms/ObjCARC/ObjCARCContract.cpp	2014-11-11 13:30:22.000000000 -0800
-+++ lib/Transforms/ObjCARC/ObjCARCContract.cpp	2015-12-01 09:48:41.817465473 -0800
-@@ -123,9 +123,10 @@
-     return false;
- 
-   // Check that the call is next to the retain.
--  BasicBlock::const_iterator I = Call;
-+  BasicBlock::const_iterator I = ++Call->getIterator();
-+  while (IsNoopInstruction(&*I))
-   ++I;
--  while (IsNoopInstruction(I)) ++I;
-+
-   if (&*I != Retain)
-     return false;
- 
-@@ -202,69 +203,166 @@
-   return true;
- }
- 
--/// Attempt to merge an objc_release with a store, load, and objc_retain to form
--/// an objc_storeStrong. This can be a little tricky because the instructions
--/// don't always appear in order, and there may be unrelated intervening
--/// instructions.
--void ObjCARCContract::ContractRelease(Instruction *Release,
--                                      inst_iterator &Iter) {
--  LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
--  if (!Load || !Load->isSimple()) return;
--
--  // For now, require everything to be in one basic block.
--  BasicBlock *BB = Release->getParent();
--  if (Load->getParent() != BB) return;
- 
--  // Walk down to find the store and the release, which may be in either order.
--  BasicBlock::iterator I = Load, End = BB->end();
--  ++I;
--  AliasAnalysis::Location Loc = AA->getLocation(Load);
-+static StoreInst* findSafeStoreForStoreStrongContraction(LoadInst *Load,
-+                                                         Instruction *Release,
-+                                                         ProvenanceAnalysis &PA,
-+                                                         AliasAnalysis *AA) {
-   StoreInst *Store = nullptr;
-   bool SawRelease = false;
--  for (; !Store || !SawRelease; ++I) {
--    if (I == End)
--      return;
- 
--    Instruction *Inst = I;
-+  // Get the location associated with Load.
-+  AliasAnalysis::Location Loc = AA->getLocation(Load);
-+
-+  // Walk down to find the store and the release, which may be in either order.
-+  for (auto I = std::next(BasicBlock::iterator(Load)),
-+            E = Load->getParent()->end();
-+       I != E; ++I) {
-+    // If we found the store we were looking for and saw the release,
-+    // break. There is no more work to be done.
-+    if (Store && SawRelease)
-+      break;
-+
-+    // Now we know that we have not seen either the store or the release. If I
-+    // is the release, mark that we saw the release and continue.
-+    Instruction *Inst = &*I;
-     if (Inst == Release) {
-       SawRelease = true;
-       continue;
-     }
- 
--    InstructionClass Class = GetBasicInstructionClass(Inst);
--
--    // Unrelated retains are harmless.
--    if (IsRetain(Class))
-+    // Otherwise, we check if Inst is a "good" store. Grab the instruction class
-+    // of Inst.
-+    InstructionClass IC = GetBasicInstructionClass(Inst);
-+
-+    // If Inst is an unrelated retain, we don't care about it.
-+    //
-+    // TODO: This is one area where the optimization could be made more
-+    // aggressive.
-+    if (IsRetain(IC))
-       continue;
- 
-+    // If we have seen the store, but not the release...
-     if (Store) {
--      // The store is the point where we're going to put the objc_storeStrong,
--      // so make sure there are no uses after it.
--      if (CanUse(Inst, Load, PA, Class))
--        return;
--    } else if (AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod) {
--      // We are moving the load down to the store, so check for anything
--      // else which writes to the memory between the load and the store.
--      Store = dyn_cast<StoreInst>(Inst);
--      if (!Store || !Store->isSimple()) return;
--      if (Store->getPointerOperand() != Loc.Ptr) return;
-+      // We need to make sure that it is safe to move the release from its
-+      // current position to the store. This implies proving that any
-+      // instruction in between Store and the Release conservatively can not use
-+      // the RCIdentityRoot of Release. If we can prove we can ignore Inst, so
-+      // continue...
-+      if (!CanUse(Inst, Load, PA, IC)) {
-+        continue;
-+      }
-+
-+      // Otherwise, be conservative and return nullptr.
-+      return nullptr;
-     }
-+
-+    // Ok, now we know we have not seen a store yet. See if Inst can write to
-+    // our load location, if it can not, just ignore the instruction.
-+    if (!(AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod))
-+      continue;
-+
-+    Store = dyn_cast<StoreInst>(Inst);
-+
-+    // If Inst can, then check if Inst is a simple store. If Inst is not a
-+    // store or a store that is not simple, then we have some we do not
-+    // understand writing to this memory implying we can not move the load
-+    // over the write to any subsequent store that we may find.
-+    if (!Store || !Store->isSimple())
-+      return nullptr;
-+
-+    // Then make sure that the pointer we are storing to is Ptr. If so, we
-+    // found our Store!
-+    if (Store->getPointerOperand() == Loc.Ptr)
-+      continue;
-+
-+    // Otherwise, we have an unknown store to some other ptr that clobbers
-+    // Loc.Ptr. Bail!
-+    return nullptr;
-   }
- 
--  Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
-+  // If we did not find the store or did not see the release, fail.
-+  if (!Store || !SawRelease)
-+    return nullptr;
-+
-+  // We succeeded!
-+  return Store;
-+}
-+
-+static Instruction*
-+findRetainForStoreStrongContraction(Value *New, StoreInst *Store,
-+                                    Instruction *Release,
-+                                    ProvenanceAnalysis &PA) {
-+  // Walk up from the Store to find the retain.
-+  BasicBlock::iterator I = Store->getIterator();
-+  BasicBlock::iterator Begin = Store->getParent()->begin();
-+  while ((I != Begin) && (GetBasicInstructionClass(&*I) != IC_Retain)) {
-+    Instruction *Inst = &*I;
-+
-+    // This is not exactly correct, but it's non-portable to 3.6.2.
-+    if (Inst != Release)
-+      return nullptr;
- 
--  // Walk up to find the retain.
--  I = Store;
--  BasicBlock::iterator Begin = BB->begin();
--  while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
-     --I;
--  Instruction *Retain = I;
--  if (GetBasicInstructionClass(Retain) != IC_Retain) return;
--  if (GetObjCArg(Retain) != New) return;
-+  }
-+
-+  Instruction *Retain = &*I;
-+  if (GetBasicInstructionClass(Retain) != IC_Retain)
-+    return nullptr;
-+
-+  if (GetObjCArg(Retain) != New)
-+    return nullptr;
-+
-+  return Retain;
-+}
-+
-+/// Attempt to merge an objc_release with a store, load, and objc_retain to form
-+/// an objc_storeStrong. This can be a little tricky because the instructions
-+/// don't always appear in order, and there may be unrelated intervening
-+/// instructions.
-+void ObjCARCContract::ContractRelease(Instruction *Release,
-+                                      inst_iterator &Iter) {
-+  // See if we are releasing something that we just loaded.
-+  auto *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
-+  if (!Load || !Load->isSimple())
-+    return;
-+
-+  // For now, require everything to be in one basic block.
-+  BasicBlock *BB = Release->getParent();
-+  if (Load->getParent() != BB)
-+    return;
-+
-+  // First scan down the BB from Load, looking for a store of the RCIdentityRoot
-+  // of Load's
-+  StoreInst *Store =
-+      findSafeStoreForStoreStrongContraction(Load, Release, PA, AA);
-+  // If we fail, bail.
-+  if (!Store)
-+    return;
-+
-+  // Then find what new_value's RCIdentity Root is.
-+  Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
-+
-+  // Then walk up the BB and look for a retain on New without any intervening
-+  // instructions which conservatively might decrement ref counts.
-+  Instruction *Retain =
-+      findRetainForStoreStrongContraction(New, Store, Release, PA);
-+
-+  // If we fail, bail.
-+  if (!Retain)
-+    return;
- 
-   Changed = true;
-   ++NumStoreStrongs;
- 
-+  DEBUG(
-+      llvm::dbgs() << "    Contracting retain, release into objc_storeStrong.\n"
-+                   << "        Old:\n"
-+                   << "            Store:   " << *Store << "\n"
-+                   << "            Release: " << *Release << "\n"
-+                   << "            Retain:  " << *Retain << "\n"
-+                   << "            Load:    " << *Load << "\n");
-+
-   LLVMContext &C = Release->getContext();
-   Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
-   Type *I8XX = PointerType::getUnqual(I8X);
-@@ -274,6 +372,7 @@
-     Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
-   if (Args[1]->getType() != I8X)
-     Args[1] = new BitCastInst(Args[1], I8X, "", Store);
-+    
-   Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_StoreStrong);
-   CallInst *StoreStrong = CallInst::Create(Decl, Args, "", Store);
-   StoreStrong->setDoesNotThrow();
-@@ -284,7 +383,11 @@
-   // we can set the tail flag once we know it's safe.
-   StoreStrongCalls.insert(StoreStrong);
- 
--  if (&*Iter == Store) ++Iter;
-+  DEBUG(llvm::dbgs() << "        New Store Strong: " << *StoreStrong << "\n");
-+
-+  if (&*Iter == Store)
-+    ++Iter;
-+  
-   Store->eraseFromParent();
-   Release->eraseFromParent();
-   EraseInstruction(Retain);
-@@ -371,7 +474,8 @@
-       // insert it now.
-       if (!RetainRVMarker)
-         break;
--      BasicBlock::iterator BBI = Inst;
-+
-+      BasicBlock::iterator BBI = Inst->getIterator();
-       BasicBlock *InstParent = Inst->getParent();
- 
-       // Step up to see if the call immediately precedes the RetainRV call.
-@@ -382,11 +486,11 @@
-           BasicBlock *Pred = InstParent->getSinglePredecessor();
-           if (!Pred)
-             goto decline_rv_optimization;
--          BBI = Pred->getTerminator();
-+          BBI = Pred->getTerminator()->getIterator();
-           break;
-         }
-         --BBI;
--      } while (IsNoopInstruction(BBI));
-+      } while (IsNoopInstruction(&*BBI));
- 
-       if (&*BBI == GetObjCArg(Inst)) {
-         DEBUG(dbgs() << "ObjCARCContract: Adding inline asm marker for "
---- lib/Transforms/ObjCARC/ObjCARCOpts.cpp	2014-12-09 10:38:53.000000000 -0800
-+++ lib/Transforms/ObjCARC/ObjCARCOpts.cpp	2016-01-23 21:53:49.000000000 -0800
-@@ -798,19 +798,22 @@
- 
- /// Enable/disable ARC sequence annotations.
- static cl::opt<bool>
--EnableARCAnnotations("enable-objc-arc-annotations", cl::init(false),
-+EnableARCAnnotations("enable-objc-arc-annotations",
-                      cl::desc("Enable emission of arc data flow analysis "
--                              "annotations"));
-+                              "annotations"),
-+                     cl::init(false));
- static cl::opt<bool>
--DisableCheckForCFGHazards("disable-objc-arc-checkforcfghazards", cl::init(false),
-+DisableCheckForCFGHazards("disable-objc-arc-checkforcfghazards",
-                           cl::desc("Disable check for cfg hazards when "
--                                   "annotating"));
-+                                   "annotating"),
-+                          cl::init(false));
-+static std::string EmptyInitString("");
- static cl::opt<std::string>
- ARCAnnotationTargetIdentifier("objc-arc-annotation-target-identifier",
--                              cl::init(""),
-                               cl::desc("filter out all data flow annotations "
-                                        "but those that apply to the given "
--                                       "target llvm identifier."));
-+                                       "target llvm identifier."),
-+                              cl::init(EmptyInitString));
- 
- /// This function appends a unique ARCAnnotationProvenanceSourceMDKind id to an
- /// instruction so that we can track backwards when post processing via the llvm
-@@ -1195,16 +1198,17 @@
-   ImmutableCallSite CS(Arg);
-   if (const Instruction *Call = CS.getInstruction()) {
-     if (Call->getParent() == RetainRV->getParent()) {
--      BasicBlock::const_iterator I = Call;
-+      BasicBlock::const_iterator I(Call);
-       ++I;
--      while (IsNoopInstruction(I)) ++I;
-+      while (IsNoopInstruction(&*I)) ++I;
-       if (&*I == RetainRV)
-         return false;
-     } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
-       BasicBlock *RetainRVParent = RetainRV->getParent();
-       if (II->getNormalDest() == RetainRVParent) {
-         BasicBlock::const_iterator I = RetainRVParent->begin();
--        while (IsNoopInstruction(I)) ++I;
-+        while (IsNoopInstruction(&*I))
-+          ++I;
-         if (&*I == RetainRV)
-           return false;
-       }
-@@ -1213,18 +1217,21 @@
- 
-   // Check for being preceded by an objc_autoreleaseReturnValue on the same
-   // pointer. In this case, we can delete the pair.
--  BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
-+  BasicBlock::iterator I = RetainRV->getIterator(),
-+                      Begin = RetainRV->getParent()->begin();
-   if (I != Begin) {
--    do --I; while (I != Begin && IsNoopInstruction(I));
--    if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
--        GetObjCArg(I) == Arg) {
-+    do
-+      --I;
-+    while (I != Begin && IsNoopInstruction(&*I));
-+    if (GetBasicInstructionClass(&*I) == IC_AutoreleaseRV &&
-+        GetObjCArg(&*I) == Arg) {
-       Changed = true;
-       ++NumPeeps;
- 
-       DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
-                    << "Erasing " << *RetainRV << "\n");
- 
--      EraseInstruction(I);
-+      EraseInstruction(&*I);
-       EraseInstruction(RetainRV);
-       return true;
-     }
-@@ -1861,9 +1868,9 @@
-         // one of its successor blocks, since we can't insert code after it
-         // in its own block, and we don't want to split critical edges.
-         if (isa<InvokeInst>(Inst))
--          S.InsertReverseInsertPt(BB->getFirstInsertionPt());
-+          S.InsertReverseInsertPt(&*BB->getFirstInsertionPt());
-         else
--          S.InsertReverseInsertPt(std::next(BasicBlock::iterator(Inst)));
-+          S.InsertReverseInsertPt(&*++Inst->getIterator());
-         S.SetSeq(S_Use);
-         ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
-       } else if (Seq == S_Release && IsUser(Class)) {
-@@ -1875,9 +1882,9 @@
-         assert(!S.HasReverseInsertPts());
-         // As above; handle invoke specially.
-         if (isa<InvokeInst>(Inst))
--          S.InsertReverseInsertPt(BB->getFirstInsertionPt());
-+          S.InsertReverseInsertPt(&*BB->getFirstInsertionPt());
-         else
--          S.InsertReverseInsertPt(std::next(BasicBlock::iterator(Inst)));
-+          S.InsertReverseInsertPt(&*++Inst->getIterator());
-       }
-       break;
-     case S_Stop:
-@@ -1934,7 +1941,7 @@
- 
-   // Visit all the instructions, bottom-up.
-   for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
--    Instruction *Inst = std::prev(I);
-+    Instruction *Inst = &*std::prev(I);
- 
-     // Invoke instructions are visited as part of their successors (below).
-     if (isa<InvokeInst>(Inst))
-@@ -2144,7 +2151,7 @@
- 
-   // Visit all the instructions, top-down.
-   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
--    Instruction *Inst = I;
-+    Instruction *Inst = &*I;
- 
-     DEBUG(dbgs() << "Visiting " << *Inst << "\n");
- 
-@@ -2219,7 +2226,7 @@
-   // as exits due to ignored edges.
-   SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
-   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
--    BasicBlock *ExitBB = I;
-+    BasicBlock *ExitBB = &*I;
-     BBState &MyStates = BBStates[ExitBB];
-     if (!MyStates.isExit())
-       continue;
-@@ -2655,7 +2662,7 @@
-     // analysis too, but that would want caching. A better approach would be to
-     // use the technique that EarlyCSE uses.
-     inst_iterator Current = std::prev(I);
--    BasicBlock *CurrentBB = Current.getBasicBlockIterator();
-+    BasicBlock *CurrentBB = &*Current.getBasicBlockIterator();
-     for (BasicBlock::iterator B = CurrentBB->begin(),
-                               J = Current.getInstructionIterator();
-          J != B; --J) {
-@@ -2910,9 +2917,8 @@
- 
-   SmallPtrSet<Instruction *, 4> DependingInstructions;
-   SmallPtrSet<const BasicBlock *, 4> Visited;
--  for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
--    BasicBlock *BB = FI;
--    ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
-+  for (BasicBlock &BB: F) {
-+    ReturnInst *Ret = dyn_cast<ReturnInst>(&BB.back());
- 
-     DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
- 
-@@ -2925,7 +2931,7 @@
-     // dependent on Arg such that there are no instructions dependent on Arg
-     // that need a positive ref count in between the autorelease and Ret.
-     CallInst *Autorelease =
--      FindPredecessorAutoreleaseWithSafePath(Arg, BB, Ret,
-+      FindPredecessorAutoreleaseWithSafePath(Arg, &BB, Ret,
-                                              DependingInstructions, Visited,
-                                              PA);
-     DependingInstructions.clear();
-@@ -2935,7 +2941,7 @@
-       continue;
- 
-     CallInst *Retain =
--      FindPredecessorRetainWithSafePath(Arg, BB, Autorelease,
-+      FindPredecessorRetainWithSafePath(Arg, &BB, Autorelease,
-                                         DependingInstructions, Visited, PA);
-     DependingInstructions.clear();
-     Visited.clear();
---- lib/Transforms/ObjCARC/ObjCARCUtil.cpp	2013-07-10 11:49:00.000000000 -0700
-+++ lib/Transforms/ObjCARC/ObjCARCUtil.cpp	2015-12-06 09:20:57.733406625 -0800
-@@ -91,7 +91,9 @@
-       .Default(IC_CallOrUser);
- 
-   // One argument.
--  const Argument *A0 = AI++;
-+  const Argument *A0 = &*AI;
-+  ++AI;
-+
-   if (AI == AE)
-     // Argument is a pointer.
-     if (PointerType *PTy = dyn_cast<PointerType>(A0->getType())) {
-@@ -127,7 +129,9 @@
-     }
- 
-   // Two arguments, first is i8**.
--  const Argument *A1 = AI++;
-+  const Argument *A1 = &*AI;
-+  ++AI;
-+
-   if (AI == AE)
-     if (PointerType *PTy = dyn_cast<PointerType>(A0->getType()))
-       if (PointerType *Pte = dyn_cast<PointerType>(PTy->getElementType()))
---- lib/Transforms/Scalar/ADCE.cpp	2014-11-18 23:49:26.000000000 -0800
-+++ lib/Transforms/Scalar/ADCE.cpp	2015-11-28 19:38:59.304881103 -0800
-@@ -63,8 +63,8 @@
-         isa<DbgInfoIntrinsic>(I.getInstructionIterator()) ||
-         isa<LandingPadInst>(I.getInstructionIterator()) ||
-         I->mayHaveSideEffects()) {
--      alive.insert(I.getInstructionIterator());
--      worklist.push_back(I.getInstructionIterator());
-+      alive.insert(&*I);
-+      worklist.push_back(&*I);
-     }
- 
-   // Propagate liveness backwards to operands.
-@@ -82,8 +82,8 @@
-   // value of the function, and may therefore be deleted safely.
-   // NOTE: We reuse the worklist vector here for memory efficiency.
-   for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
--    if (!alive.count(I.getInstructionIterator())) {
--      worklist.push_back(I.getInstructionIterator());
-+    if (!alive.count(&*I)) {
-+      worklist.push_back(&*I);
-       I->dropAllReferences();
-     }
- 
---- lib/Transforms/Scalar/ConstantHoisting.cpp	2014-10-04 09:55:56.000000000 -0700
-+++ lib/Transforms/Scalar/ConstantHoisting.cpp	2015-11-28 19:44:37.366065720 -0800
-@@ -361,9 +361,9 @@
- /// into an instruction itself.
- void ConstantHoisting::collectConstantCandidates(Function &Fn) {
-   ConstCandMapType ConstCandMap;
--  for (Function::iterator BB : Fn)
--    for (BasicBlock::iterator Inst : *BB)
--      collectConstantCandidates(ConstCandMap, Inst);
-+  for (BasicBlock &BB : Fn)
-+    for (Instruction &Inst : BB)
-+      collectConstantCandidates(ConstCandMap, &Inst);
- }
- 
- /// \brief Find the base constant within the given range and rebase all other
---- lib/Transforms/Scalar/CorrelatedValuePropagation.cpp	2014-09-07 13:29:59.000000000 -0700
-+++ lib/Transforms/Scalar/CorrelatedValuePropagation.cpp	2015-11-28 19:45:51.045707253 -0800
-@@ -296,7 +296,8 @@
-   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
-     bool BBChanged = false;
-     for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) {
--      Instruction *II = BI++;
-+      Instruction *II = &*BI;
-+      ++BI;
-       switch (II->getOpcode()) {
-       case Instruction::Select:
-         BBChanged |= processSelect(cast<SelectInst>(II));
---- lib/Transforms/Scalar/DCE.cpp	2014-04-21 19:55:47.000000000 -0700
-+++ lib/Transforms/Scalar/DCE.cpp	2015-11-28 19:46:43.738032658 -0800
-@@ -45,7 +45,8 @@
-       TargetLibraryInfo *TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
-       bool Changed = false;
-       for (BasicBlock::iterator DI = BB.begin(); DI != BB.end(); ) {
--        Instruction *Inst = DI++;
-+        Instruction *Inst = &*DI;
-+        ++DI;
-         if (isInstructionTriviallyDead(Inst, TLI)) {
-           Inst->eraseFromParent();
-           Changed = true;
---- lib/Transforms/Scalar/DeadStoreElimination.cpp	2014-10-17 04:56:00.000000000 -0700
-+++ lib/Transforms/Scalar/DeadStoreElimination.cpp	2015-11-28 20:06:21.344415630 -0800
-@@ -64,11 +64,11 @@
-       TLI = AA->getTargetLibraryInfo();
- 
-       bool Changed = false;
--      for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
-+      for (BasicBlock &I : F)
-         // Only check non-dead blocks.  Dead blocks may have strange pointer
-         // cycles that will confuse alias analysis.
--        if (DT->isReachableFromEntry(I))
--          Changed |= runOnBasicBlock(*I);
-+        if (DT->isReachableFromEntry(&I))
-+          Changed |= runOnBasicBlock(I);
- 
-       AA = nullptr; MD = nullptr; DT = nullptr;
-       return Changed;
-@@ -488,7 +488,8 @@
- 
-   // Do a top-down walk on the BB.
-   for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) {
--    Instruction *Inst = BBI++;
-+    Instruction *Inst = &*BBI;
-+    ++BBI;
- 
-     // Handle 'free' calls specially.
-     if (CallInst *F = isFreeCall(Inst, TLI)) {
-@@ -518,7 +519,7 @@
- 
-           // DeleteDeadInstruction can delete the current instruction.  Save BBI
-           // in case we need it.
--          WeakVH NextInst(BBI);
-+          WeakVH NextInst(&*BBI);
- 
-           DeleteDeadInstruction(SI, *MD, TLI);
- 
-@@ -573,7 +574,7 @@
- 
-           // DeleteDeadInstruction can delete the current instruction in loop
-           // cases, reset BBI.
--          BBI = Inst;
-+          BBI = Inst->getIterator();
-           if (BBI != BB.begin())
-             --BBI;
-           break;
-@@ -619,7 +620,8 @@
-       if (AA->getModRefInfo(DepWrite, Loc) & AliasAnalysis::Ref)
-         break;
- 
--      InstDep = MD->getPointerDependencyFrom(Loc, false, DepWrite, &BB);
-+      InstDep = MD->getPointerDependencyFrom(Loc, false,
-+                                             DepWrite->getIterator(), &BB);
-     }
-   }
- 
-@@ -661,7 +663,8 @@
-     Instruction *InstPt = BB->getTerminator();
-     if (BB == F->getParent()) InstPt = F;
- 
--    MemDepResult Dep = MD->getPointerDependencyFrom(Loc, false, InstPt, BB);
-+    MemDepResult Dep = MD->getPointerDependencyFrom(Loc, false,
-+                                                    InstPt->getIterator(), BB);
-     while (Dep.isDef() || Dep.isClobber()) {
-       Instruction *Dependency = Dep.getInst();
-       if (!hasMemoryWrite(Dependency, TLI) || !isRemovable(Dependency))
-@@ -674,7 +677,7 @@
-       if (!AA->isMustAlias(F->getArgOperand(0), DepPointer))
-         break;
- 
--      Instruction *Next = std::next(BasicBlock::iterator(Dependency));
-+      Instruction *Next = &*std::next(BasicBlock::iterator(Dependency));
- 
-       // DCE instructions only used to calculate that store
-       DeleteDeadInstruction(Dependency, *MD, TLI);
-@@ -686,7 +689,7 @@
-       //    s[0] = 0;
-       //    s[1] = 0; // This has just been deleted.
-       //    free(s);
--      Dep = MD->getPointerDependencyFrom(Loc, false, Next, BB);
-+      Dep = MD->getPointerDependencyFrom(Loc, false, Next->getIterator(), BB);
-     }
- 
-     if (Dep.isNonLocal())
-@@ -710,33 +713,32 @@
-   SmallSetVector<Value*, 16> DeadStackObjects;
- 
-   // Find all of the alloca'd pointers in the entry block.
--  BasicBlock *Entry = BB.getParent()->begin();
--  for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I) {
--    if (isa<AllocaInst>(I))
--      DeadStackObjects.insert(I);
-+  BasicBlock &Entry = BB.getParent()->front();
-+  for (Instruction &I : Entry) {
-+    if (isa<AllocaInst>(&I))
-+      DeadStackObjects.insert(&I);
- 
-     // Okay, so these are dead heap objects, but if the pointer never escapes
-     // then it's leaked by this function anyways.
--    else if (isAllocLikeFn(I, TLI) && !PointerMayBeCaptured(I, true, true))
--      DeadStackObjects.insert(I);
-+    else if (isAllocLikeFn(&I, TLI) && !PointerMayBeCaptured(&I, true, true))
-+      DeadStackObjects.insert(&I);
-   }
- 
-   // Treat byval or inalloca arguments the same, stores to them are dead at the
-   // end of the function.
--  for (Function::arg_iterator AI = BB.getParent()->arg_begin(),
--       AE = BB.getParent()->arg_end(); AI != AE; ++AI)
--    if (AI->hasByValOrInAllocaAttr())
--      DeadStackObjects.insert(AI);
-+  for (Argument &AI : BB.getParent()->args())
-+    if (AI.hasByValOrInAllocaAttr())
-+      DeadStackObjects.insert(&AI);
- 
-   // Scan the basic block backwards
-   for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
-     --BBI;
- 
-     // If we find a store, check to see if it points into a dead stack value.
--    if (hasMemoryWrite(BBI, TLI) && isRemovable(BBI)) {
-+    if (hasMemoryWrite(&*BBI, TLI) && isRemovable(&*BBI)) {
-       // See through pointer-to-pointer bitcasts
-       SmallVector<Value *, 4> Pointers;
--      GetUnderlyingObjects(getStoredPointerOperand(BBI), Pointers);
-+      GetUnderlyingObjects(getStoredPointerOperand(&*BBI), Pointers);
- 
-       // Stores to stack values are valid candidates for removal.
-       bool AllDead = true;
-@@ -748,7 +750,8 @@
-         }
- 
-       if (AllDead) {
--        Instruction *Dead = BBI++;
-+        Instruction *Dead = &*BBI;
-+        ++BBI;
- 
-         DEBUG(dbgs() << "DSE: Dead Store at End of Block:\n  DEAD: "
-                      << *Dead << "\n  Objects: ";
-@@ -769,8 +772,9 @@
-     }
- 
-     // Remove any dead non-memory-mutating instructions.
--    if (isInstructionTriviallyDead(BBI, TLI)) {
--      Instruction *Inst = BBI++;
-+    if (isInstructionTriviallyDead(&*BBI, TLI)) {
-+      Instruction *Inst = &*BBI;
-+      ++BBI;
-       DeleteDeadInstruction(Inst, *MD, TLI, &DeadStackObjects);
-       ++NumFastOther;
-       MadeChange = true;
-@@ -780,15 +784,15 @@
-     if (isa<AllocaInst>(BBI)) {
-       // Remove allocas from the list of dead stack objects; there can't be
-       // any references before the definition.
--      DeadStackObjects.remove(BBI);
-+      DeadStackObjects.remove(&*BBI);
-       continue;
-     }
- 
-     if (CallSite CS = cast<Value>(BBI)) {
-       // Remove allocation function calls from the list of dead stack objects; 
-       // there can't be any references before the definition.
--      if (isAllocLikeFn(BBI, TLI))
--        DeadStackObjects.remove(BBI);
-+      if (isAllocLikeFn(&*BBI, TLI))
-+        DeadStackObjects.remove(&*BBI);
- 
-       // If this call does not access memory, it can't be loading any of our
-       // pointers.
---- lib/Transforms/Scalar/EarlyCSE.cpp	2015-02-10 18:23:00.000000000 -0800
-+++ lib/Transforms/Scalar/EarlyCSE.cpp	2015-11-28 20:08:04.692689072 -0800
-@@ -427,7 +427,8 @@
-   // See if any instructions in the block can be eliminated.  If so, do it.  If
-   // not, add them to AvailableValues.
-   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
--    Instruction *Inst = I++;
-+    Instruction *Inst = &*I;
-+    ++I;
- 
-     // Dead instructions should just be removed.
-     if (isInstructionTriviallyDead(Inst, TLI)) {
---- lib/Transforms/Scalar/FlattenCFGPass.cpp	2014-04-21 19:55:47.000000000 -0700
-+++ lib/Transforms/Scalar/FlattenCFGPass.cpp	2015-11-28 20:09:20.884486852 -0800
-@@ -59,7 +59,7 @@
-     // Loop over all of the basic blocks and remove them if they are unneeded...
-     //
-     for (Function::iterator BBIt = F.begin(); BBIt != F.end();) {
--      if (FlattenCFG(BBIt++, AA)) {
-+      if (FlattenCFG(&*BBIt++, AA)) {
-         LocalChange = true;
-       }
-     }
---- lib/Transforms/Scalar/GVN.cpp	2015-05-05 07:43:00.000000000 -0700
-+++ lib/Transforms/Scalar/GVN.cpp	2015-11-28 20:13:21.312881435 -0800
-@@ -1123,7 +1123,7 @@
-   uint64_t StoreSize = (DL.getTypeSizeInBits(SrcVal->getType()) + 7) / 8;
-   uint64_t LoadSize = (DL.getTypeSizeInBits(LoadTy) + 7) / 8;
- 
--  IRBuilder<> Builder(InsertPt->getParent(), InsertPt);
-+  IRBuilder<> Builder(InsertPt);
- 
-   // Compute which bits of the stored value are being used by the load.  Convert
-   // to an integer type to start with.
-@@ -1220,7 +1220,7 @@
-   LLVMContext &Ctx = LoadTy->getContext();
-   uint64_t LoadSize = DL.getTypeSizeInBits(LoadTy)/8;
- 
--  IRBuilder<> Builder(InsertPt->getParent(), InsertPt);
-+  IRBuilder<> Builder(InsertPt);
- 
-   // We know that this method is only called when the mem transfer fully
-   // provides the bits for the load.
-@@ -2372,7 +2372,8 @@
-   // Merge unconditional branches, allowing PRE to catch more
-   // optimization opportunities.
-   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
--    BasicBlock *BB = FI++;
-+    BasicBlock *BB = &*FI;
-+    ++FI;
- 
-     bool removedBlock = MergeBlockIntoPredecessor(BB, this);
-     if (removedBlock) ++NumGVNBlocks;
-@@ -2425,7 +2426,7 @@
- 
-   for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
-        BI != BE;) {
--    ChangedFunction |= processInstruction(BI);
-+    ChangedFunction |= processInstruction(&*BI);
-     if (InstrsToErase.empty()) {
-       ++BI;
-       continue;
-@@ -2580,7 +2581,8 @@
-   // Create a PHI to make the value available in this block.
-   PHINode *Phi =
-       PHINode::Create(CurInst->getType(), predMap.size(),
--                      CurInst->getName() + ".pre-phi", CurrentBlock->begin());
-+                      CurInst->getName() + ".pre-phi",
-+                      &CurrentBlock->front());
-   for (unsigned i = 0, e = predMap.size(); i != e; ++i) {
-     if (Value *V = predMap[i].first)
-       Phi->addIncoming(V, predMap[i].second);
-@@ -2631,7 +2633,8 @@
-     for (BasicBlock::iterator BI = CurrentBlock->begin(),
-                               BE = CurrentBlock->end();
-          BI != BE;) {
--      Instruction *CurInst = BI++;
-+      Instruction *CurInst = &*BI;
-+      ++BI;
-       Changed = performScalarPRE(CurInst);
-     }
-   }
---- lib/Transforms/Scalar/IndVarSimplify.cpp	2014-11-18 23:49:26.000000000 -0800
-+++ lib/Transforms/Scalar/IndVarSimplify.cpp	2015-11-29 07:09:51.854588965 -0800
-@@ -435,7 +435,7 @@
-   // platforms.
-   if (WeakPH) {
-     Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
--                                 PN->getParent()->getFirstInsertionPt());
-+                                 &*PN->getParent()->getFirstInsertionPt());
-     PN->replaceAllUsesWith(Conv);
-     RecursivelyDeleteTriviallyDeadInstructions(PN, TLI);
-   }
-@@ -998,7 +998,7 @@
-           PHINode::Create(DU.WideDef->getType(), 1, UsePhi->getName() + ".wide",
-                           UsePhi);
-         WidePhi->addIncoming(DU.WideDef, UsePhi->getIncomingBlock(0));
--        IRBuilder<> Builder(WidePhi->getParent()->getFirstInsertionPt());
-+        IRBuilder<> Builder(&*WidePhi->getParent()->getFirstInsertionPt());
-         Value *Trunc = Builder.CreateTrunc(WidePhi, DU.NarrowDef->getType());
-         UsePhi->replaceAllUsesWith(Trunc);
-         DeadInsts.push_back(UsePhi);
-@@ -1149,7 +1149,7 @@
-   // either find an existing phi or materialize a new one. Either way, we
-   // expect a well-formed cyclic phi-with-increments. i.e. any operand not part
-   // of the phi-SCC dominates the loop entry.
--  Instruction *InsertPt = L->getHeader()->begin();
-+  Instruction *InsertPt = &L->getHeader()->front();
-   WidePhi = cast<PHINode>(Rewriter.expandCodeFor(AddRec, WideType, InsertPt));
- 
-   // Remembering the WideIV increment generated by SCEVExpander allows
-@@ -1835,8 +1835,8 @@
-   BasicBlock *Preheader = L->getLoopPreheader();
-   if (!Preheader) return;
- 
--  Instruction *InsertPt = ExitBlock->getFirstInsertionPt();
--  BasicBlock::iterator I = Preheader->getTerminator();
-+  Instruction *InsertPt = &*ExitBlock->getFirstInsertionPt();
-+  BasicBlock::iterator I(Preheader->getTerminator());
-   while (I != Preheader->begin()) {
-     --I;
-     // New instructions were inserted at the end of the preheader.
-@@ -1889,7 +1889,7 @@
-       continue;
- 
-     // Otherwise, sink it to the exit block.
--    Instruction *ToMove = I;
-+    Instruction *ToMove = &*I;
-     bool Done = false;
- 
-     if (I != Preheader->begin()) {
---- lib/Transforms/Scalar/JumpThreading.cpp	2015-01-12 19:46:47.000000000 -0800
-+++ lib/Transforms/Scalar/JumpThreading.cpp	2015-11-29 07:18:33.215512385 -0800
-@@ -179,7 +179,7 @@
-   do {
-     Changed = false;
-     for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
--      BasicBlock *BB = I;
-+      BasicBlock *BB = &*I;
-       // Thread all of the branches we can over this block.
-       while (ProcessBlock(BB))
-         Changed = true;
-@@ -242,7 +242,7 @@
- static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB,
-                                              unsigned Threshold) {
-   /// Ignore PHI nodes, these will be flattened when duplication happens.
--  BasicBlock::const_iterator I = BB->getFirstNonPHI();
-+  BasicBlock::const_iterator I(BB->getFirstNonPHI());
- 
-   // FIXME: THREADING will delete values that are just used to compute the
-   // branch, so they shouldn't count against the duplication cost.
-@@ -890,7 +890,7 @@
- 
-   // Scan a few instructions up from the load, to see if it is obviously live at
-   // the entry to its block.
--  BasicBlock::iterator BBIt = LI;
-+  BasicBlock::iterator BBIt(LI);
- 
-   if (Value *AvailableVal =
-         FindAvailableLoadedValue(LoadedPtr, LoadBB, BBIt, 6)) {
-@@ -1019,7 +1019,7 @@
-   // Create a PHI node at the start of the block for the PRE'd load value.
-   pred_iterator PB = pred_begin(LoadBB), PE = pred_end(LoadBB);
-   PHINode *PN = PHINode::Create(LI->getType(), std::distance(PB, PE), "",
--                                LoadBB->begin());
-+                                &LoadBB->front());
-   PN->takeName(LI);
-   PN->setDebugLoc(LI->getDebugLoc());
- 
-@@ -1449,7 +1449,7 @@
-     Instruction *New = BI->clone();
-     New->setName(BI->getName());
-     NewBB->getInstList().push_back(New);
--    ValueMapping[BI] = New;
-+    ValueMapping[&*BI] = New;
- 
-     // Remap operands to patch up intra-block references.
-     for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
-@@ -1499,8 +1499,8 @@
-     // its block to be uses of the appropriate PHI node etc.  See ValuesInBlocks
-     // with the two values we know.
-     SSAUpdate.Initialize(I->getType(), I->getName());
--    SSAUpdate.AddAvailableValue(BB, I);
--    SSAUpdate.AddAvailableValue(NewBB, ValueMapping[I]);
-+    SSAUpdate.AddAvailableValue(BB, &*I);
-+    SSAUpdate.AddAvailableValue(NewBB, ValueMapping[&*I]);
- 
-     while (!UsesToRename.empty())
-       SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
-@@ -1605,12 +1605,12 @@
-     // phi translation.
-     if (Value *IV = SimplifyInstruction(New, DL)) {
-       delete New;
--      ValueMapping[BI] = IV;
-+      ValueMapping[&*BI] = IV;
-     } else {
-       // Otherwise, insert the new instruction into the block.
-       New->setName(BI->getName());
--      PredBB->getInstList().insert(OldPredBranch, New);
--      ValueMapping[BI] = New;
-+      PredBB->getInstList().insert(OldPredBranch->getIterator(), New);
-+      ValueMapping[&*BI] = New;
-     }
-   }
- 
-@@ -1652,8 +1652,8 @@
-     // its block to be uses of the appropriate PHI node etc.  See ValuesInBlocks
-     // with the two values we know.
-     SSAUpdate.Initialize(I->getType(), I->getName());
--    SSAUpdate.AddAvailableValue(BB, I);
--    SSAUpdate.AddAvailableValue(PredBB, ValueMapping[I]);
-+    SSAUpdate.AddAvailableValue(BB, &*I);
-+    SSAUpdate.AddAvailableValue(PredBB, ValueMapping[&*I]);
- 
-     while (!UsesToRename.empty())
-       SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
---- lib/Transforms/Scalar/LICM.cpp	2014-12-29 15:00:57.000000000 -0800
-+++ lib/Transforms/Scalar/LICM.cpp	2015-11-27 19:41:29.442793583 -0800
-@@ -573,7 +573,7 @@
-         if (!OLoop->contains(&PN)) {
-           PHINode *OpPN =
-               PHINode::Create(OInst->getType(), PN.getNumIncomingValues(),
--                              OInst->getName() + ".lcssa", ExitBlock.begin());
-+                              OInst->getName() + ".lcssa", &ExitBlock.front());
-           for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
-             OpPN->addIncoming(OInst, PN.getIncomingBlock(i));
-           *OI = OpPN;
-@@ -720,7 +720,7 @@
-             // store that.
-             PHINode *PN = PHINode::Create(
-                 I->getType(), PredCache.GetNumPreds(BB),
--                I->getName() + ".lcssa", BB->begin());
-+                I->getName() + ".lcssa", &BB->front());
-             for (BasicBlock **PI = PredCache.GetPreds(BB); *PI; ++PI)
-               PN->addIncoming(I, *PI);
-             return PN;
-@@ -916,7 +916,7 @@
-     CurLoop->getUniqueExitBlocks(ExitBlocks);
-     InsertPts.resize(ExitBlocks.size());
-     for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
--      InsertPts[i] = ExitBlocks[i]->getFirstInsertionPt();
-+      InsertPts[i] = &*ExitBlocks[i]->getFirstInsertionPt();
-   }
- 
-   // We use the SSAUpdater interface to insert phi nodes as required.
---- lib/Transforms/Scalar/LoopIdiomRecognize.cpp	2014-06-13 20:48:29.000000000 -0700
-+++ lib/Transforms/Scalar/LoopIdiomRecognize.cpp	2015-11-29 07:21:21.325412485 -0800
-@@ -441,9 +441,9 @@
-   // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
-   {
-     CountInst = nullptr;
--    for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI(),
-+    for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(),
-            IterE = LoopEntry->end(); Iter != IterE; Iter++) {
--      Instruction *Inst = Iter;
-+      Instruction *Inst = &*Iter;
-       if (Inst->getOpcode() != Instruction::Add)
-         continue;
- 
-@@ -571,7 +571,7 @@
-     ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
-     Type *Ty = TripCnt->getType();
- 
--    PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", Body->begin());
-+    PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &(Body->front()));
- 
-     Builder.SetInsertPoint(LbCond);
-     Value *Opnd1 = cast<Value>(TcPhi);
-@@ -736,10 +736,12 @@
- 
-   bool MadeChange = false;
-   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
--    Instruction *Inst = I++;
-+    Instruction *Inst = &*I;
-+    ++I;
-+
-     // Look for store instructions, which may be optimized to memset/memcpy.
-     if (StoreInst *SI = dyn_cast<StoreInst>(Inst))  {
--      WeakVH InstPtr(I);
-+      WeakVH InstPtr(&*I);
-       if (!processLoopStore(SI, BECount)) continue;
-       MadeChange = true;
- 
-@@ -752,7 +754,7 @@
- 
-     // Look for memset instructions, which may be optimized to a larger memset.
-     if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst))  {
--      WeakVH InstPtr(I);
-+      WeakVH InstPtr(&*I);
-       if (!processLoopMemSet(MSI, BECount)) continue;
-       MadeChange = true;
- 
-@@ -891,8 +893,7 @@
-   for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
-        ++BI)
-     for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
--      if (&*I != IgnoredStore &&
--          (AA.getModRefInfo(I, StoreLoc) & Access))
-+      if (&*I != IgnoredStore && (AA.getModRefInfo(&*I, StoreLoc) & Access))
-         return true;
- 
-   return false;
---- lib/Transforms/Scalar/LoopInstSimplify.cpp	2015-01-28 09:35:18.000000000 -0800
-+++ lib/Transforms/Scalar/LoopInstSimplify.cpp	2015-11-28 15:26:59.128054267 -0800
-@@ -112,7 +112,8 @@
- 
-       // Simplify instructions in the current basic block.
-       for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
--        Instruction *I = BI++;
-+        Instruction *I = &*BI;
-+        BI++;
- 
-         // The first time through the loop ToSimplify is empty and we try to
-         // simplify all instructions. On later iterations ToSimplify is not
---- lib/Transforms/Scalar/LoopRerollPass.cpp	2014-10-28 04:54:52.000000000 -0700
-+++ lib/Transforms/Scalar/LoopRerollPass.cpp	2015-11-29 07:34:50.826695128 -0800
-@@ -373,7 +373,7 @@
-       continue;
- 
-     if (const SCEVAddRecExpr *PHISCEV =
--        dyn_cast<SCEVAddRecExpr>(SE->getSCEV(I))) {
-+        dyn_cast<SCEVAddRecExpr>(SE->getSCEV(&*I))) {
-       if (PHISCEV->getLoop() != L)
-         continue;
-       if (!PHISCEV->isAffine())
-@@ -387,7 +387,7 @@
- 
-         DEBUG(dbgs() << "LRR: Possible IV: " << *I << " = " <<
-               *PHISCEV << "\n");
--        PossibleIVs.push_back(I);
-+        PossibleIVs.push_back(&*I);
-       }
-     }
-   }
-@@ -445,7 +445,7 @@
-     if (!I->getType()->isSingleValueType())
-       continue;
- 
--    SimpleLoopReduction SLR(I, L);
-+    SimpleLoopReduction SLR(&*I, L);
-     if (!SLR.valid())
-       continue;
- 
-@@ -856,35 +856,36 @@
-         continue;
-       if (cast<Instruction>(J1) == IV)
-         continue;
--      if (!BaseUseSet.count(J1))
-+      if (!BaseUseSet.count(&*J1))
-         continue;
--      if (PossibleRedPHISet.count(J1)) // Skip reduction PHIs.
-+      if (PossibleRedPHISet.count(&*J1)) // Skip reduction PHIs.
-         continue;
- 
--      while (J2 != JE && (!RootUseSet.count(J2) ||
-+      while (J2 != JE && (!RootUseSet.count(&*J2) ||
-              std::find(Roots[i].begin(), Roots[i].end(), J2) !=
-                Roots[i].end())) {
-         // As we iterate through the instructions, instructions that don't
-         // belong to previous iterations (or the base case), must belong to
-         // future iterations. We want to track the alias set of writes from
-         // previous iterations.
--        if (!isa<PHINode>(J2) && !BaseUseSet.count(J2) &&
--            !AllRootUses.count(J2)) {
-+        if (!isa<PHINode>(J2) && !BaseUseSet.count(&*J2) &&
-+            !AllRootUses.count(&*J2)) {
-           if (J2->mayWriteToMemory())
--            AST.add(J2);
-+            AST.add(&*J2);
- 
-           // Note: This is specifically guarded by a check on isa<PHINode>,
-           // which while a valid (somewhat arbitrary) micro-optimization, is
-           // needed because otherwise isSafeToSpeculativelyExecute returns
-           // false on PHI nodes.
--          if (!isSimpleLoadStore(J2) && !isSafeToSpeculativelyExecute(J2, DL))
-+          if (!isSimpleLoadStore(&*J2) &&
-+              !isSafeToSpeculativelyExecute(&*J2, DL))
-             FutureSideEffects = true;
-         }
- 
-         ++J2;
-       }
- 
--      if (!J1->isSameOperationAs(J2)) {
-+      if (!J1->isSameOperationAs(&*J2)) {
-         DEBUG(dbgs() << "LRR: iteration root match failed at " << *J1 <<
-                         " vs. " << *J2 << "\n");
-         MatchFailed = true;
-@@ -894,7 +895,7 @@
-       // Make sure that this instruction, which is in the use set of this
-       // root instruction, does not also belong to the base set or the set of
-       // some previous root instruction.
--      if (BaseUseSet.count(J2) || AllRootUses.count(J2)) {
-+      if (BaseUseSet.count(&*J2) || AllRootUses.count(&*J2)) {
-         DEBUG(dbgs() << "LRR: iteration root match failed at " << *J1 <<
-                         " vs. " << *J2 << " (prev. case overlap)\n");
-         MatchFailed = true;
-@@ -907,7 +908,7 @@
-       if (J2->mayReadFromMemory()) {
-         for (AliasSetTracker::iterator K = AST.begin(), KE = AST.end();
-              K != KE && !MatchFailed; ++K) {
--          if (K->aliasesUnknownInst(J2, *AA)) {
-+          if (K->aliasesUnknownInst(&*J2, *AA)) {
-             DEBUG(dbgs() << "LRR: iteration root match failed at " << *J1 <<
-                             " vs. " << *J2 << " (depends on future store)\n");
-             MatchFailed = true;
-@@ -921,10 +922,10 @@
-       // them, and this matching fails. As an exception, we allow the alias
-       // set tracker to handle regular (simple) load/store dependencies.
-       if (FutureSideEffects &&
--            ((!isSimpleLoadStore(J1) &&
--              !isSafeToSpeculativelyExecute(J1, DL)) ||
--             (!isSimpleLoadStore(J2) &&
--              !isSafeToSpeculativelyExecute(J2, DL)))) {
-+            ((!isSimpleLoadStore(&*J1) &&
-+              !isSafeToSpeculativelyExecute(&*J1, &*DL)) ||
-+             (!isSimpleLoadStore(&*J2) &&
-+              !isSafeToSpeculativelyExecute(&*J2, &*DL)))) {
-         DEBUG(dbgs() << "LRR: iteration root match failed at " << *J1 <<
-                         " vs. " << *J2 <<
-                         " (side effects prevent reordering)\n");
-@@ -942,7 +943,7 @@
-       //   x += a[i]; x += b[i];
-       //   x += a[i+1]; x += b[i+1];
-       //   x += b[i+2]; x += a[i+2];
--      bool InReduction = Reductions.isPairInSame(J1, J2);
-+      bool InReduction = Reductions.isPairInSame(&*J1, &*J2);
- 
-       if (!(InReduction && J1->isAssociative())) {
-         bool Swapped = false, SomeOpMatched = false;
-@@ -954,7 +955,7 @@
-           // part of the reduction.
-           if (InReduction)
-             if (Instruction *Op2I = dyn_cast<Instruction>(Op2))
--              if (Reductions.isPairInSame(J2, Op2I))
-+              if (Reductions.isPairInSame(&*J2, Op2I))
-                 continue;
- 
-           DenseMap<Value *, Value *>::iterator BMI = BaseMap.find(Op2);
-@@ -985,8 +986,8 @@
-         }
-       }
- 
--      if ((!PossibleRedLastSet.count(J1) && hasUsesOutsideLoop(J1, L)) ||
--          (!PossibleRedLastSet.count(J2) && hasUsesOutsideLoop(J2, L))) {
-+      if ((!PossibleRedLastSet.count(&*J1) && hasUsesOutsideLoop(&*J1, L)) ||
-+          (!PossibleRedLastSet.count(&*J2) && hasUsesOutsideLoop(&*J2, L))) {
-         DEBUG(dbgs() << "LRR: iteration root match failed at " << *J1 <<
-                         " vs. " << *J2 << " (uses outside loop)\n");
-         MatchFailed = true;
-@@ -994,10 +995,10 @@
-       }
- 
-       if (!MatchFailed)
--        BaseMap.insert(std::pair<Value *, Value *>(J2, J1));
-+        BaseMap.insert(std::pair<Value *, Value *>(&*J2, &*J1));
- 
--      AllRootUses.insert(J2);
--      Reductions.recordPair(J1, J2, i+1);
-+      AllRootUses.insert(&*J2);
-+      Reductions.recordPair(&*J1, &*J2, i+1);
- 
-       ++J2;
-     }
-@@ -1025,15 +1026,15 @@
-       continue;
-     if (cast<Instruction>(J) == IV)
-       continue;
--    if (BaseUseSet.count(J) || AllRootUses.count(J) ||
--        (LoopIncUseSet.count(J) && (J->isTerminator() ||
--                                    isSafeToSpeculativelyExecute(J, DL))))
-+    if (BaseUseSet.count(&*J) || AllRootUses.count(&*J) ||
-+        (LoopIncUseSet.count(&*J) && (J->isTerminator() ||
-+                                    isSafeToSpeculativelyExecute(&*J, &*DL))))
-       continue;
- 
--    if (AllRoots.count(J))
-+    if (AllRoots.count(&*J))
-       continue;
- 
--    if (Reductions.isSelectedPHI(J))
-+    if (Reductions.isSelectedPHI(&*J))
-       continue;
- 
-     DEBUG(dbgs() << "LRR: aborting reroll based on " << *RealIV <<
-@@ -1080,7 +1081,7 @@
-                            L, SCEV::FlagAnyWrap));
-   { // Limit the lifetime of SCEVExpander.
-     SCEVExpander Expander(*SE, "reroll");
--    Value *NewIV = Expander.expandCodeFor(H, IV->getType(), Header->begin());
-+    Value *NewIV = Expander.expandCodeFor(H, IV->getType(), &(Header->front()));
- 
-     for (DenseSet<Instruction *>::iterator J = BaseUseSet.begin(),
-          JE = BaseUseSet.end(); J != JE; ++J)
---- lib/Transforms/Scalar/LoopRotation.cpp	2015-03-09 13:26:36.000000000 -0700
-+++ lib/Transforms/Scalar/LoopRotation.cpp	2015-11-29 08:53:24.120179108 -0800
-@@ -141,7 +141,7 @@
-   // as necessary.
-   SSAUpdater SSA;
-   for (I = OrigHeader->begin(); I != E; ++I) {
--    Value *OrigHeaderVal = I;
-+    Value *OrigHeaderVal = &*I;
- 
-     // If there are no uses of the value (e.g. because it returns void), there
-     // is nothing to rewrite.
-@@ -203,8 +203,7 @@
-     MultiExitLoop = true;
- 
-   for (BasicBlock::iterator I = Begin; I != End; ++I) {
--
--    if (!isSafeToSpeculativelyExecute(I))
-+    if (!isSafeToSpeculativelyExecute(&*I))
-       return false;
- 
-     if (isa<DbgInfoIntrinsic>(I))
-@@ -287,14 +286,15 @@
-   if (!BI)
-     return false;
- 
--  if (!shouldSpeculateInstrs(Latch->begin(), Jmp, L))
-+  if (!shouldSpeculateInstrs(Latch->begin(), Jmp->getIterator(), L))
-     return false;
- 
-   DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
-         << LastExit->getName() << "\n");
- 
-   // Hoist the instructions from Latch into LastExit.
--  LastExit->getInstList().splice(BI, Latch->getInstList(), Latch->begin(), Jmp);
-+  LastExit->getInstList().splice(BI->getIterator(), Latch->getInstList(),
-+                                 Latch->begin(), Jmp->getIterator());
- 
-   unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
-   BasicBlock *Header = Jmp->getSuccessor(0);
-@@ -416,7 +416,8 @@
-   // possible or create a clone in the OldPreHeader if not.
-   TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
-   while (I != E) {
--    Instruction *Inst = I++;
-+    Instruction *Inst = &*I;
-+    ++I;
- 
-     // If the instruction's operands are invariant and it doesn't read or write
-     // memory, then it is safe to hoist.  Doing this doesn't change the order of
---- lib/Transforms/Scalar/LoopStrengthReduce.cpp	2014-11-18 23:49:26.000000000 -0800
-+++ lib/Transforms/Scalar/LoopStrengthReduce.cpp	2015-11-29 08:54:51.641136545 -0800
-@@ -1933,9 +1933,10 @@
-       // NOTE: we could handle setcc instructions with multiple uses here, but
-       // InstCombine does it as well for simple uses, it's not clear that it
-       // occurs enough in real life to handle.
--      CondUse = UI;
-+      CondUse = &*UI;
-       return true;
-     }
-+
-   return false;
- }
- 
-@@ -2203,7 +2204,7 @@
-         ICmpInst *OldCond = Cond;
-         Cond = cast<ICmpInst>(Cond->clone());
-         Cond->setName(L->getHeader()->getName() + ".termcond");
--        ExitingBlock->getInstList().insert(TermBr, Cond);
-+        ExitingBlock->getInstList().insert(TermBr->getIterator(), Cond);
- 
-         // Clone the IVUse, as the old use still exists!
-         CondUse = &IU.AddUser(Cond, CondUse->getOperandValToReplace());
-@@ -2782,20 +2783,21 @@
-     for (BasicBlock::iterator I = (*BBIter)->begin(), E = (*BBIter)->end();
-          I != E; ++I) {
-       // Skip instructions that weren't seen by IVUsers analysis.
--      if (isa<PHINode>(I) || !IU.isIVUserOrOperand(I))
-+      if (isa<PHINode>(I) || !IU.isIVUserOrOperand(&*I))
-         continue;
- 
-       // Ignore users that are part of a SCEV expression. This way we only
-       // consider leaf IV Users. This effectively rediscovers a portion of
-       // IVUsers analysis but in program order this time.
--      if (SE.isSCEVable(I->getType()) && !isa<SCEVUnknown>(SE.getSCEV(I)))
-+      if (SE.isSCEVable(I->getType()) && !isa<SCEVUnknown>(SE.getSCEV(&*I)))
-         continue;
- 
-       // Remove this instruction from any NearUsers set it may be in.
-       for (unsigned ChainIdx = 0, NChains = IVChainVec.size();
-            ChainIdx < NChains; ++ChainIdx) {
--        ChainUsersVec[ChainIdx].NearUsers.erase(I);
-+        ChainUsersVec[ChainIdx].NearUsers.erase(&*I);
-       }
-+
-       // Search for operands that can be chained.
-       SmallPtrSet<Instruction*, 4> UniqueOperands;
-       User::op_iterator IVOpEnd = I->op_end();
-@@ -2803,7 +2805,7 @@
-       while (IVOpIter != IVOpEnd) {
-         Instruction *IVOpInst = cast<Instruction>(*IVOpIter);
-         if (UniqueOperands.insert(IVOpInst).second)
--          ChainInstruction(I, IVOpInst, ChainUsersVec);
-+          ChainInstruction(&*I, IVOpInst, ChainUsersVec);
-         IVOpIter = findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE);
-       }
-     } // Continue walking down the instructions.
-@@ -4437,14 +4439,14 @@
-       // instead of at the end, so that it can be used for other expansions.
-       if (IDom == Inst->getParent() &&
-           (!BetterPos || !DT.dominates(Inst, BetterPos)))
--        BetterPos = std::next(BasicBlock::iterator(Inst));
-+        BetterPos = &(*std::next(BasicBlock::iterator(Inst)));
-     }
-     if (!AllDominate)
-       break;
-     if (BetterPos)
--      IP = BetterPos;
-+      IP = BetterPos->getIterator();
-     else
--      IP = Tentative;
-+      IP = Tentative->getIterator();
-   }
- 
-   return IP;
-@@ -4511,7 +4513,8 @@
-   // Set IP below instructions recently inserted by SCEVExpander. This keeps the
-   // IP consistent across expansions and allows the previously inserted
-   // instructions to be reused by subsequent expansion.
--  while (Rewriter.isInsertedInstruction(IP) && IP != LowestIP) ++IP;
-+  while (Rewriter.isInsertedInstruction(&*IP) && IP != LowestIP)
-+    ++IP;
- 
-   return IP;
- }
-@@ -4563,7 +4566,7 @@
-                                  LF.UserInst, LF.OperandValToReplace,
-                                  Loops, SE, DT);
- 
--    Ops.push_back(SE.getUnknown(Rewriter.expandCodeFor(Reg, nullptr, IP)));
-+    Ops.push_back(SE.getUnknown(Rewriter.expandCodeFor(Reg, nullptr, &*IP)));
-   }
- 
-   // Expand the ScaledReg portion.
-@@ -4581,14 +4584,14 @@
-       // Expand ScaleReg as if it was part of the base regs.
-       if (F.Scale == 1)
-         Ops.push_back(
--            SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr, IP)));
-+            SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr, &*IP)));
-       else {
-         // An interesting way of "folding" with an icmp is to use a negated
-         // scale, which we'll implement by inserting it into the other operand
-         // of the icmp.
-         assert(F.Scale == -1 &&
-                "The only scale supported by ICmpZero uses is -1!");
--        ICmpScaledV = Rewriter.expandCodeFor(ScaledS, nullptr, IP);
-+        ICmpScaledV = Rewriter.expandCodeFor(ScaledS, nullptr, &*IP);
-       }
-     } else {
-       // Otherwise just expand the scaled register and an explicit scale,
-@@ -4598,11 +4601,11 @@
-       // Unless the addressing mode will not be folded.
-       if (!Ops.empty() && LU.Kind == LSRUse::Address &&
-           isAMCompletelyFolded(TTI, LU, F)) {
--        Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
-+        Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, &*IP);
-         Ops.clear();
-         Ops.push_back(SE.getUnknown(FullV));
-       }
--      ScaledS = SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr, IP));
-+      ScaledS = SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr, &*IP));
-       if (F.Scale != 1)
-         ScaledS =
-             SE.getMulExpr(ScaledS, SE.getConstant(ScaledS->getType(), F.Scale));
-@@ -4614,7 +4617,7 @@
-   if (F.BaseGV) {
-     // Flush the operand list to suppress SCEVExpander hoisting.
-     if (!Ops.empty()) {
--      Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
-+      Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, &*IP);
-       Ops.clear();
-       Ops.push_back(SE.getUnknown(FullV));
-     }
-@@ -4624,7 +4627,7 @@
-   // Flush the operand list to suppress SCEVExpander hoisting of both folded and
-   // unfolded offsets. LSR assumes they both live next to their uses.
-   if (!Ops.empty()) {
--    Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
-+    Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, &*IP);
-     Ops.clear();
-     Ops.push_back(SE.getUnknown(FullV));
-   }
-@@ -4636,7 +4639,7 @@
-       // The other interesting way of "folding" with an ICmpZero is to use a
-       // negated immediate.
-       if (!ICmpScaledV)
--        ICmpScaledV = ConstantInt::get(IntTy, -(uint64_t)Offset);
-+        ICmpScaledV = ConstantInt::get(IntTy, -((uint64_t) Offset));
-       else {
-         Ops.push_back(SE.getUnknown(ICmpScaledV));
-         ICmpScaledV = ConstantInt::get(IntTy, Offset);
-@@ -4660,7 +4663,7 @@
-   const SCEV *FullS = Ops.empty() ?
-                       SE.getConstant(IntTy, 0) :
-                       SE.getAddExpr(Ops);
--  Value *FullV = Rewriter.expandCodeFor(FullS, Ty, IP);
-+  Value *FullV = Rewriter.expandCodeFor(FullS, Ty, &*IP);
- 
-   // We're done expanding now, so reset the rewriter.
-   Rewriter.clearPostInc();
-@@ -4759,7 +4762,8 @@
-       if (!Pair.second)
-         PN->setIncomingValue(i, Pair.first->second);
-       else {
--        Value *FullV = Expand(LF, F, BB->getTerminator(), Rewriter, DeadInsts);
-+        Value *FullV = Expand(LF, F, BB->getTerminator()->getIterator(),
-+                              Rewriter, DeadInsts);
- 
-         // If this is reuse-by-noop-cast, insert the noop cast.
-         Type *OpTy = LF.OperandValToReplace->getType();
-@@ -4789,7 +4793,8 @@
-   if (PHINode *PN = dyn_cast<PHINode>(LF.UserInst)) {
-     RewriteForPHI(PN, LF, F, Rewriter, DeadInsts, P);
-   } else {
--    Value *FullV = Expand(LF, F, LF.UserInst, Rewriter, DeadInsts);
-+    Value *FullV =
-+      Expand(LF, F, LF.UserInst->getIterator(), Rewriter, DeadInsts);
- 
-     // If this is reuse-by-noop-cast, insert the noop cast.
-     Type *OpTy = LF.OperandValToReplace->getType();
---- lib/Transforms/Scalar/LoopUnswitch.cpp	2015-01-04 04:03:27.000000000 -0800
-+++ lib/Transforms/Scalar/LoopUnswitch.cpp	2015-11-28 17:55:30.857922905 -0800
-@@ -737,7 +737,7 @@
-   // without actually branching to it (the exit block should be dominated by the
-   // loop header, not the preheader).
-   assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
--  BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), this);
-+  BasicBlock *NewExit = SplitBlock(ExitBlock, &(ExitBlock->front()), this);
- 
-   // Okay, now we have a position to branch from and a position to branch to,
-   // insert the new conditional branch.
-@@ -832,8 +832,9 @@
- 
-   // Splice the newly inserted blocks into the function right before the
-   // original preheader.
--  F->getBasicBlockList().splice(NewPreheader, F->getBasicBlockList(),
--                                NewBlocks[0], F->end());
-+  F->getBasicBlockList().splice(NewPreheader->getIterator(),
-+                                F->getBasicBlockList(),
-+                                NewBlocks[0]->getIterator(), F->end());
- 
-   // FIXME: We could register any cloned assumptions instead of clearing the
-   // whole function's cache.
-@@ -875,7 +876,7 @@
- 
-     if (LandingPadInst *LPad = NewExit->getLandingPadInst()) {
-       PHINode *PN = PHINode::Create(LPad->getType(), 0, "",
--                                    ExitSucc->getFirstInsertionPt());
-+                                    &*ExitSucc->getFirstInsertionPt());
- 
-       for (pred_iterator I = pred_begin(ExitSucc), E = pred_end(ExitSucc);
-            I != E; ++I) {
-@@ -891,7 +892,8 @@
-   for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
-     for (BasicBlock::iterator I = NewBlocks[i]->begin(),
-            E = NewBlocks[i]->end(); I != E; ++I)
--      RemapInstruction(I, VMap,RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
-+      RemapInstruction(&*I, VMap,
-+                       RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
- 
-   // Rewrite the original preheader to select between versions of the loop.
-   BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
-@@ -1136,8 +1138,9 @@
-         Succ->replaceAllUsesWith(Pred);
- 
-         // Move all of the successor contents from Succ to Pred.
--        Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
--                                   Succ->end());
-+        Pred->getInstList().splice(BI->getIterator(),
-+                                   Succ->getInstList(),
-+                                   Succ->begin(), Succ->end());
-         LPM->deleteSimpleAnalysisValue(BI, L);
-         BI->eraseFromParent();
-         RemoveFromWorklist(BI, Worklist);
---- lib/Transforms/Scalar/LowerAtomic.cpp	2014-06-13 07:24:07.000000000 -0700
-+++ lib/Transforms/Scalar/LowerAtomic.cpp	2015-11-28 17:57:32.665949990 -0800
-@@ -22,7 +22,7 @@
- #define DEBUG_TYPE "loweratomic"
- 
- static bool LowerAtomicCmpXchgInst(AtomicCmpXchgInst *CXI) {
--  IRBuilder<> Builder(CXI->getParent(), CXI);
-+  IRBuilder<> Builder(CXI);
-   Value *Ptr = CXI->getPointerOperand();
-   Value *Cmp = CXI->getCompareOperand();
-   Value *Val = CXI->getNewValOperand();
-@@ -41,7 +41,7 @@
- }
- 
- static bool LowerAtomicRMWInst(AtomicRMWInst *RMWI) {
--  IRBuilder<> Builder(RMWI->getParent(), RMWI);
-+  IRBuilder<> Builder(RMWI);
-   Value *Ptr = RMWI->getPointerOperand();
-   Value *Val = RMWI->getValOperand();
- 
-@@ -120,7 +120,8 @@
-         return false;
-       bool Changed = false;
-       for (BasicBlock::iterator DI = BB.begin(), DE = BB.end(); DI != DE; ) {
--        Instruction *Inst = DI++;
-+        Instruction *Inst = &*DI;
-+        ++DI;
-         if (FenceInst *FI = dyn_cast<FenceInst>(Inst))
-           Changed |= LowerFenceInst(FI);
-         else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(Inst))
---- lib/Transforms/Scalar/MemCpyOptimizer.cpp	2015-02-07 11:39:14.000000000 -0800
-+++ lib/Transforms/Scalar/MemCpyOptimizer.cpp	2015-11-28 18:08:18.813257513 -0800
-@@ -385,7 +385,7 @@
-   // are stored.
-   MemsetRanges Ranges(*DL);
- 
--  BasicBlock::iterator BI = StartInst;
-+  BasicBlock::iterator BI(StartInst);
-   for (++BI; !isa<TerminatorInst>(BI); ++BI) {
-     if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
-       // If the instruction is readnone, ignore it, otherwise bail out.  We
-@@ -440,7 +440,7 @@
-   // If we create any memsets, we put it right before the first instruction that
-   // isn't part of the memset block.  This ensure that the memset is dominated
-   // by any addressing instruction needed by the start of the block.
--  IRBuilder<> Builder(BI);
-+  IRBuilder<> Builder(&*BI);
- 
-   // Now that we have full information about ranges, loop over the ranges and
-   // emit memset's for anything big enough to be worthwhile.
-@@ -513,8 +513,8 @@
-         // the call and the store.
-         AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
-         AliasAnalysis::Location StoreLoc = AA.getLocation(SI);
--        for (BasicBlock::iterator I = --BasicBlock::iterator(SI),
--                                  E = C; I != E; --I) {
-+        for (BasicBlock::iterator I = --SI->getIterator(),
-+                                  E = C->getIterator(); I != E; --I) {
-           if (AA.getModRefInfo(&*I, StoreLoc) != AliasAnalysis::NoModRef) {
-             C = nullptr;
-             break;
-@@ -556,7 +556,7 @@
-   if (Value *ByteVal = isBytewiseValue(SI->getOperand(0)))
-     if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(),
-                                               ByteVal)) {
--      BBI = I;  // Don't invalidate iterator.
-+      BBI = I->getIterator();  // Don't invalidate iterator.
-       return true;
-     }
- 
-@@ -569,7 +569,7 @@
-   if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile())
-     if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(),
-                                               MSI->getValue())) {
--      BBI = I;  // Don't invalidate iterator.
-+      BBI = I->getIterator();  // Don't invalidate iterator.
-       return true;
-     }
-   return false;
-@@ -808,8 +808,8 @@
-   // NOTE: This is conservative, it will stop on any read from the source loc,
-   // not just the defining memcpy.
-   MemDepResult SourceDep =
--    MD->getPointerDependencyFrom(AA.getLocationForSource(MDep),
--                                 false, M, M->getParent());
-+    MD->getPointerDependencyFrom(AA.getLocationForSource(MDep), false,
-+                                 M->getIterator(), M->getParent());
-   if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
-     return false;
- 
-@@ -898,8 +898,9 @@
-   }
- 
-   AliasAnalysis::Location SrcLoc = AliasAnalysis::getLocationForSource(M);
--  MemDepResult SrcDepInfo = MD->getPointerDependencyFrom(SrcLoc, true,
--                                                         M, M->getParent());
-+  MemDepResult SrcDepInfo =
-+    MD->getPointerDependencyFrom(SrcLoc, true,
-+                                 M->getIterator(), M->getParent());
-   if (SrcDepInfo.isClobber()) {
-     if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(SrcDepInfo.getInst()))
-       return processMemCpyMemCpyDependence(M, MDep, CopySize->getZExtValue());
-@@ -967,7 +968,8 @@
-   uint64_t ByValSize = DL->getTypeAllocSize(ByValTy);
-   MemDepResult DepInfo =
-     MD->getPointerDependencyFrom(AliasAnalysis::Location(ByValArg, ByValSize),
--                                 true, CS.getInstruction(),
-+                                 true,
-+                                 CS.getInstruction()->getIterator(),
-                                  CS.getInstruction()->getParent());
-   if (!DepInfo.isClobber())
-     return false;
-@@ -1012,7 +1014,9 @@
-   // not just the defining memcpy.
-   MemDepResult SourceDep =
-     MD->getPointerDependencyFrom(AliasAnalysis::getLocationForSource(MDep),
--                                 false, CS.getInstruction(), MDep->getParent());
-+                                 false,
-+                                 CS.getInstruction()->getIterator(),
-+                                 MDep->getParent());
-   if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
-     return false;
- 
-@@ -1039,7 +1043,8 @@
-   for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
-     for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
-       // Avoid invalidating the iterator.
--      Instruction *I = BI++;
-+      Instruction *I = &*BI;
-+      ++BI;
- 
-       bool RepeatInstruction = false;
- 
---- lib/Transforms/Scalar/MergedLoadStoreMotion.cpp	2015-02-17 14:03:58.000000000 -0800
-+++ lib/Transforms/Scalar/MergedLoadStoreMotion.cpp	2015-11-28 18:11:58.690419443 -0800
-@@ -256,7 +256,7 @@
- 
-   for (BasicBlock::iterator BBI = BB1->begin(), BBE = BB1->end(); BBI != BBE;
-        ++BBI) {
--    Instruction *Inst = BBI;
-+    Instruction *Inst = &*BBI;
- 
-     // Only merge and hoist loads when their result in used only in BB
-     if (!isa<LoadInst>(Inst) || Inst->isUsedOutsideOfBlock(BB1))
-@@ -367,8 +367,7 @@
-   int NLoads = 0;
-   for (BasicBlock::iterator BBI = Succ0->begin(), BBE = Succ0->end();
-        BBI != BBE;) {
--
--    Instruction *I = BBI;
-+    Instruction *I = &*BBI;
-     ++BBI;
- 
-     // Only move non-simple (atomic, volatile) loads.
-@@ -448,7 +447,7 @@
-   Value *Opd2 = S1->getValueOperand();
-   if (Opd1 != Opd2) {
-     NewPN = PHINode::Create(Opd1->getType(), 2, Opd2->getName() + ".sink",
--                            BB->begin());
-+                            &BB->front());
-     NewPN->addIncoming(Opd1, S0->getParent());
-     NewPN->addIncoming(Opd2, S1->getParent());
-     if (NewPN->getType()->getScalarType()->isPointerTy()) {
-@@ -493,7 +492,7 @@
-     StoreInst *SNew = (StoreInst *)(S0->clone());
-     Instruction *ANew = A0->clone();
-     AA->copyValue(S0, SNew);
--    SNew->insertBefore(InsertPt);
-+    SNew->insertBefore(&*InsertPt);
-     ANew->insertBefore(SNew);
- 
-     assert(S0->getParent() == A0->getParent());
-@@ -588,7 +587,8 @@
-   // Merge unconditional branches, allowing PRE to catch more
-   // optimization opportunities.
-   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
--    BasicBlock *BB = FI++;
-+    BasicBlock *BB = &*FI;
-+    ++FI;
- 
-     // Hoist equivalent loads and sink stores
-     // outside diamonds when possible
---- lib/Transforms/Scalar/PartiallyInlineLibCalls.cpp	2014-08-01 16:21:21.000000000 -0700
-+++ lib/Transforms/Scalar/PartiallyInlineLibCalls.cpp	2015-11-28 18:13:26.025414765 -0800
-@@ -152,7 +152,7 @@
-   Phi->addIncoming(Call, &CurrBB);
-   Phi->addIncoming(LibCall, LibCallBB);
- 
--  BB = JoinBB;
-+  BB = JoinBB->getIterator();
-   return true;
- }
- 
---- lib/Transforms/Scalar/Reassociate.cpp	2014-12-12 06:44:12.000000000 -0800
-+++ lib/Transforms/Scalar/Reassociate.cpp	2015-11-29 08:56:09.229859750 -0800
-@@ -295,7 +295,7 @@
-     // we cannot move.  This ensures that the ranks for these instructions are
-     // all different in the block.
-     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
--      if (isUnmovableInstruction(I))
-+      if (isUnmovableInstruction(&*I))
-         ValueRankMap[&*I] = ++BBRank;
-   }
- }
-@@ -968,14 +968,14 @@
-       if (InvokeInst *II = dyn_cast<InvokeInst>(InstInput)) {
-         InsertPt = II->getNormalDest()->begin();
-       } else {
--        InsertPt = InstInput;
--        ++InsertPt;
-+        InsertPt = ++InstInput->getIterator();
-       }
-       while (isa<PHINode>(InsertPt)) ++InsertPt;
-     } else {
-       InsertPt = TheNeg->getParent()->getParent()->getEntryBlock().begin();
-     }
--    TheNeg->moveBefore(InsertPt);
-+
-+    TheNeg->moveBefore(&*InsertPt);
-     return TheNeg;
-   }
- 
-@@ -1160,7 +1160,7 @@
-     return nullptr;
-   }
- 
--  BasicBlock::iterator InsertPt = BO; ++InsertPt;
-+  BasicBlock::iterator InsertPt = ++BO->getIterator();
- 
-   // If this was just a single multiply, remove the multiply and return the only
-   // remaining operand.
-@@ -1173,7 +1173,7 @@
-   }
- 
-   if (NeedsNegate)
--    V = CreateNeg(V, "neg", InsertPt, BO);
-+    V = CreateNeg(V, "neg", &*InsertPt, BO);
- 
-   return V;
- }
-@@ -2262,10 +2262,10 @@
-   for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
-     // Optimize every instruction in the basic block.
-     for (BasicBlock::iterator II = BI->begin(), IE = BI->end(); II != IE; )
--      if (isInstructionTriviallyDead(II)) {
--        EraseInst(II++);
-+      if (isInstructionTriviallyDead(&*II)) {
-+        EraseInst(&*II++);
-       } else {
--        OptimizeInst(II);
-+        OptimizeInst(&*II);
-         assert(II->getParent() == BI && "Moved to a different block!");
-         ++II;
-       }
---- lib/Transforms/Scalar/Reg2Mem.cpp	2015-01-12 19:46:47.000000000 -0800
-+++ lib/Transforms/Scalar/Reg2Mem.cpp	2015-11-28 18:22:35.790368260 -0800
-@@ -85,7 +85,7 @@
-   CastInst *AllocaInsertionPoint =
-     new BitCastInst(Constant::getNullValue(Type::getInt32Ty(F.getContext())),
-                     Type::getInt32Ty(F.getContext()),
--                    "reg2mem alloca point", I);
-+                    "reg2mem alloca point", &*I);
- 
-   // Find the escaped instructions. But don't create stack slots for
-   // allocas in entry block.
-@@ -95,7 +95,7 @@
-     for (BasicBlock::iterator iib = ibb->begin(), iie = ibb->end();
-          iib != iie; ++iib) {
-       if (!(isa<AllocaInst>(iib) && iib->getParent() == BBEntry) &&
--          valueEscapes(iib)) {
-+          valueEscapes(&*iib)) {
-         WorkList.push_front(&*iib);
-       }
-     }
---- lib/Transforms/Scalar/SCCP.cpp	2014-11-18 23:49:26.000000000 -0800
-+++ lib/Transforms/Scalar/SCCP.cpp	2015-11-28 19:12:24.103813993 -0800
-@@ -1125,7 +1125,7 @@
-   // entry block executable and merge in the actual arguments to the call into
-   // the formal arguments of the function.
-   if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){
--    MarkBlockExecutable(F->begin());
-+    MarkBlockExecutable(&F->front());
- 
-     // Propagate information from this call site into the callee.
-     CallSite::arg_iterator CAI = CS.arg_begin();
-@@ -1134,17 +1134,17 @@
-       // If this argument is byval, and if the function is not readonly, there
-       // will be an implicit copy formed of the input aggregate.
-       if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
--        markOverdefined(AI);
-+        markOverdefined(&*AI);
-         continue;
-       }
- 
-       if (StructType *STy = dyn_cast<StructType>(AI->getType())) {
-         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
-           LatticeVal CallArg = getStructValueState(*CAI, i);
--          mergeInValue(getStructValueState(AI, i), AI, CallArg);
-+          mergeInValue(getStructValueState(&*AI, i), &*AI, CallArg);
-         }
-       } else {
--        mergeInValue(AI, getValueState(*CAI));
-+        mergeInValue(&*AI, getValueState(*CAI));
-       }
-     }
-   }
-@@ -1245,18 +1245,18 @@
- /// even if X isn't defined.
- bool SCCPSolver::ResolvedUndefsIn(Function &F) {
-   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
--    if (!BBExecutable.count(BB))
-+    if (!BBExecutable.count(&*BB))
-       continue;
- 
--    for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
-+    for (Instruction &I : *BB) {
-       // Look for instructions which produce undef values.
--      if (I->getType()->isVoidTy()) continue;
-+      if (I.getType()->isVoidTy()) continue;
- 
--      if (StructType *STy = dyn_cast<StructType>(I->getType())) {
-+      if (StructType *STy = dyn_cast<StructType>(I.getType())) {
-         // Only a few things that can be structs matter for undef.
- 
-         // Tracked calls must never be marked overdefined in ResolvedUndefsIn.
--        if (CallSite CS = CallSite(I))
-+        if (CallSite CS = CallSite(&I))
-           if (Function *F = CS.getCalledFunction())
-             if (MRVFunctionsTracked.count(F))
-               continue;
-@@ -1269,14 +1269,14 @@
-         // Send the results of everything else to overdefined.  We could be
-         // more precise than this but it isn't worth bothering.
-         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
--          LatticeVal &LV = getStructValueState(I, i);
-+          LatticeVal &LV = getStructValueState(&I, i);
-           if (LV.isUndefined())
--            markOverdefined(LV, I);
-+            markOverdefined(LV, &I);
-         }
-         continue;
-       }
- 
--      LatticeVal &LV = getValueState(I);
-+      LatticeVal &LV = getValueState(&I);
-       if (!LV.isUndefined()) continue;
- 
-       // extractvalue is safe; check here because the argument is a struct.
-@@ -1286,24 +1286,24 @@
-       // Compute the operand LatticeVals, for convenience below.
-       // Anything taking a struct is conservatively assumed to require
-       // overdefined markings.
--      if (I->getOperand(0)->getType()->isStructTy()) {
--        markOverdefined(I);
-+      if (I.getOperand(0)->getType()->isStructTy()) {
-+        markOverdefined(&I);
-         return true;
-       }
--      LatticeVal Op0LV = getValueState(I->getOperand(0));
-+      LatticeVal Op0LV = getValueState(I.getOperand(0));
-       LatticeVal Op1LV;
--      if (I->getNumOperands() == 2) {
--        if (I->getOperand(1)->getType()->isStructTy()) {
--          markOverdefined(I);
-+      if (I.getNumOperands() == 2) {
-+        if (I.getOperand(1)->getType()->isStructTy()) {
-+          markOverdefined(&I);
-           return true;
-         }
- 
--        Op1LV = getValueState(I->getOperand(1));
-+        Op1LV = getValueState(I.getOperand(1));
-       }
-       // If this is an instructions whose result is defined even if the input is
-       // not fully defined, propagate the information.
--      Type *ITy = I->getType();
--      switch (I->getOpcode()) {
-+      Type *ITy = I.getType();
-+      switch (I.getOpcode()) {
-       case Instruction::Add:
-       case Instruction::Sub:
-       case Instruction::Trunc:
-@@ -1317,9 +1317,9 @@
-       case Instruction::FRem:
-         // Floating-point binary operation: be conservative.
-         if (Op0LV.isUndefined() && Op1LV.isUndefined())
--          markForcedConstant(I, Constant::getNullValue(ITy));
-+          markForcedConstant(&I, Constant::getNullValue(ITy));
-         else
--          markOverdefined(I);
-+          markOverdefined(&I);
-         return true;
-       case Instruction::ZExt:
-       case Instruction::SExt:
-@@ -1331,7 +1331,7 @@
-       case Instruction::SIToFP:
-       case Instruction::UIToFP:
-         // undef -> 0; some outputs are impossible
--        markForcedConstant(I, Constant::getNullValue(ITy));
-+        markForcedConstant(&I, Constant::getNullValue(ITy));
-         return true;
-       case Instruction::Mul:
-       case Instruction::And:
-@@ -1340,7 +1340,7 @@
-           break;
-         // undef * X -> 0.   X could be zero.
-         // undef & X -> 0.   X could be zero.
--        markForcedConstant(I, Constant::getNullValue(ITy));
-+        markForcedConstant(&I, Constant::getNullValue(ITy));
-         return true;
- 
-       case Instruction::Or:
-@@ -1348,7 +1348,7 @@
-         if (Op0LV.isUndefined() && Op1LV.isUndefined())
-           break;
-         // undef | X -> -1.   X could be -1.
--        markForcedConstant(I, Constant::getAllOnesValue(ITy));
-+        markForcedConstant(&I, Constant::getAllOnesValue(ITy));
-         return true;
- 
-       case Instruction::Xor:
-@@ -1356,7 +1356,7 @@
-         // necessary, but we try to be nice to people who expect this
-         // behavior in simple cases
-         if (Op0LV.isUndefined() && Op1LV.isUndefined()) {
--          markForcedConstant(I, Constant::getNullValue(ITy));
-+          markForcedConstant(&I, Constant::getNullValue(ITy));
-           return true;
-         }
-         // undef ^ X -> undef
-@@ -1372,7 +1372,7 @@
- 
-         // undef / X -> 0.   X could be maxint.
-         // undef % X -> 0.   X could be 1.
--        markForcedConstant(I, Constant::getNullValue(ITy));
-+        markForcedConstant(&I, Constant::getNullValue(ITy));
-         return true;
- 
-       case Instruction::AShr:
-@@ -1380,7 +1380,7 @@
-         if (Op1LV.isUndefined()) break;
- 
-         // undef >>a X -> all ones
--        markForcedConstant(I, Constant::getAllOnesValue(ITy));
-+        markForcedConstant(&I, Constant::getAllOnesValue(ITy));
-         return true;
-       case Instruction::LShr:
-       case Instruction::Shl:
-@@ -1390,17 +1390,17 @@
- 
-         // undef << X -> 0
-         // undef >> X -> 0
--        markForcedConstant(I, Constant::getNullValue(ITy));
-+        markForcedConstant(&I, Constant::getNullValue(ITy));
-         return true;
-       case Instruction::Select:
--        Op1LV = getValueState(I->getOperand(1));
-+        Op1LV = getValueState(I.getOperand(1));
-         // undef ? X : Y  -> X or Y.  There could be commonality between X/Y.
-         if (Op0LV.isUndefined()) {
-           if (!Op1LV.isConstant())  // Pick the constant one if there is any.
--            Op1LV = getValueState(I->getOperand(2));
-+            Op1LV = getValueState(I.getOperand(2));
-         } else if (Op1LV.isUndefined()) {
-           // c ? undef : undef -> undef.  No change.
--          Op1LV = getValueState(I->getOperand(2));
-+          Op1LV = getValueState(I.getOperand(2));
-           if (Op1LV.isUndefined())
-             break;
-           // Otherwise, c ? undef : x -> x.
-@@ -1409,9 +1409,9 @@
-         }
- 
-         if (Op1LV.isConstant())
--          markForcedConstant(I, Op1LV.getConstant());
-+          markForcedConstant(&I, Op1LV.getConstant());
-         else
--          markOverdefined(I);
-+          markOverdefined(&I);
-         return true;
-       case Instruction::Load:
-         // A load here means one of two things: a load of undef from a global,
-@@ -1420,9 +1420,9 @@
-         break;
-       case Instruction::ICmp:
-         // X == undef -> undef.  Other comparisons get more complicated.
--        if (cast<ICmpInst>(I)->isEquality())
-+        if (cast<ICmpInst>(&I)->isEquality())
-           break;
--        markOverdefined(I);
-+        markOverdefined(&I);
-         return true;
-       case Instruction::Call:
-       case Instruction::Invoke: {
-@@ -1431,19 +1431,19 @@
-         // 2. It could be constant-foldable.
-         // Because of the way we solve return values, tracked calls must
-         // never be marked overdefined in ResolvedUndefsIn.
--        if (Function *F = CallSite(I).getCalledFunction())
-+        if (Function *F = CallSite(&I).getCalledFunction())
-           if (TrackedRetVals.count(F))
-             break;
- 
-         // If the call is constant-foldable, we mark it overdefined because
-         // we do not know what return values are valid.
--        markOverdefined(I);
-+        markOverdefined(&I);
-         return true;
-       }
-       default:
-         // If we don't know what should happen here, conservatively mark it
-         // overdefined.
--        markOverdefined(I);
-+        markOverdefined(&I);
-         return true;
-       }
-     }
-@@ -1461,7 +1461,7 @@
-       // false.
-       if (isa<UndefValue>(BI->getCondition())) {
-         BI->setCondition(ConstantInt::getFalse(BI->getContext()));
--        markEdgeExecutable(BB, TI->getSuccessor(1));
-+        markEdgeExecutable(&*BB, TI->getSuccessor(1));
-         return true;
-       }
- 
-@@ -1483,7 +1483,7 @@
-       // the first constant.
-       if (isa<UndefValue>(SI->getCondition())) {
-         SI->setCondition(SI->case_begin().getCaseValue());
--        markEdgeExecutable(BB, SI->case_begin().getCaseSuccessor());
-+        markEdgeExecutable(&*BB, SI->case_begin().getCaseSuccessor());
-         return true;
-       }
- 
-@@ -1540,8 +1540,7 @@
-   Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
-   while (EndInst != BB->begin()) {
-     // Delete the next to last instruction.
--    BasicBlock::iterator I = EndInst;
--    Instruction *Inst = --I;
-+    Instruction *Inst = &*--EndInst->getIterator();
-     if (!Inst->use_empty())
-       Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
-     if (isa<LandingPadInst>(Inst)) {
-@@ -1567,11 +1566,11 @@
-   SCCPSolver Solver(DL, TLI);
- 
-   // Mark the first block of the function as being executable.
--  Solver.MarkBlockExecutable(F.begin());
-+  Solver.MarkBlockExecutable(&F.front());
- 
-   // Mark all arguments to the function as being overdefined.
--  for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
--    Solver.markAnythingOverdefined(AI);
-+  for (Argument &AI : F.args())
-+    Solver.markAnythingOverdefined(&AI);
- 
-   // Solve for constants.
-   bool ResolvedUndefs = true;
-@@ -1588,8 +1587,8 @@
-   // as we cannot modify the CFG of the function.
- 
-   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
--    if (!Solver.isBlockExecutable(BB)) {
--      DeleteInstructionInBlock(BB);
-+    if (!Solver.isBlockExecutable(&*BB)) {
-+      DeleteInstructionInBlock(&*BB);
-       MadeChanges = true;
-       continue;
-     }
-@@ -1598,7 +1597,7 @@
-     // constants if we have found them to be of constant values.
-     //
-     for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
--      Instruction *Inst = BI++;
-+      Instruction *Inst = &*BI++;
-       if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
-         continue;
- 
-@@ -1712,36 +1711,34 @@
-     // If this is a strong or ODR definition of this function, then we can
-     // propagate information about its result into callsites of it.
-     if (!F->mayBeOverridden())
--      Solver.AddTrackedFunction(F);
-+      Solver.AddTrackedFunction(&*F);
- 
-     // If this function only has direct calls that we can see, we can track its
-     // arguments and return value aggressively, and can assume it is not called
-     // unless we see evidence to the contrary.
-     if (F->hasLocalLinkage()) {
--      if (AddressIsTaken(F))
--        AddressTakenFunctions.insert(F);
-+      if (AddressIsTaken(&*F))
-+        AddressTakenFunctions.insert(&*F);
-       else {
--        Solver.AddArgumentTrackedFunction(F);
-+        Solver.AddArgumentTrackedFunction(&*F);
-         continue;
-       }
-     }
- 
-     // Assume the function is called.
--    Solver.MarkBlockExecutable(F->begin());
-+    Solver.MarkBlockExecutable(&F->front());
- 
-     // Assume nothing about the incoming arguments.
--    for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
--         AI != E; ++AI)
--      Solver.markAnythingOverdefined(AI);
-+    for (Argument &AI : F->args())
-+      Solver.markAnythingOverdefined(&AI);
-   }
- 
-   // Loop over global variables.  We inform the solver about any internal global
-   // variables that do not have their 'addresses taken'.  If they don't have
-   // their addresses taken, we can propagate constants through them.
--  for (Module::global_iterator G = M.global_begin(), E = M.global_end();
--       G != E; ++G)
--    if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
--      Solver.TrackValueOfGlobalVariable(G);
-+  for (GlobalVariable &G : M.globals())
-+    if (!G.isConstant() && G.hasLocalLinkage() && !AddressIsTaken(&G))
-+      Solver.TrackValueOfGlobalVariable(&G);
- 
-   // Solve for constants.
-   bool ResolvedUndefs = true;
-@@ -1762,7 +1759,10 @@
-   SmallVector<BasicBlock*, 512> BlocksToErase;
- 
-   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
--    if (Solver.isBlockExecutable(F->begin())) {
-+    if (F->isDeclaration())
-+      continue;
-+
-+    if (Solver.isBlockExecutable(&F->front())) {
-       for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
-            AI != E; ++AI) {
-         if (AI->use_empty() || AI->getType()->isStructTy()) continue;
-@@ -1770,7 +1770,7 @@
-         // TODO: Could use getStructLatticeValueFor to find out if the entire
-         // result is a constant and replace it entirely if so.
- 
--        LatticeVal IV = Solver.getLatticeValueFor(AI);
-+        LatticeVal IV = Solver.getLatticeValueFor(&*AI);
-         if (IV.isOverdefined()) continue;
- 
-         Constant *CST = IV.isConstant() ?
-@@ -1785,29 +1785,29 @@
-     }
- 
-     for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
--      if (!Solver.isBlockExecutable(BB)) {
--        DeleteInstructionInBlock(BB);
-+      if (!Solver.isBlockExecutable(&*BB)) {
-+        DeleteInstructionInBlock(&*BB);
-         MadeChanges = true;
- 
-         TerminatorInst *TI = BB->getTerminator();
-         for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
-           BasicBlock *Succ = TI->getSuccessor(i);
-           if (!Succ->empty() && isa<PHINode>(Succ->begin()))
--            TI->getSuccessor(i)->removePredecessor(BB);
-+            TI->getSuccessor(i)->removePredecessor(&*BB);
-         }
-+
-         if (!TI->use_empty())
-           TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
-         TI->eraseFromParent();
-+        new UnreachableInst(M.getContext(), &*BB);
- 
-         if (&*BB != &F->front())
--          BlocksToErase.push_back(BB);
--        else
--          new UnreachableInst(M.getContext(), BB);
-+          BlocksToErase.push_back(&*BB);
-         continue;
-       }
- 
-       for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
--        Instruction *Inst = BI++;
-+        Instruction *Inst = &*BI++;
-         if (Inst->getType()->isVoidTy() || Inst->getType()->isStructTy())
-           continue;
- 
---- lib/Transforms/Scalar/SROA.cpp	2015-01-07 18:02:00.000000000 -0800
-+++ lib/Transforms/Scalar/SROA.cpp	2015-11-28 19:22:34.615193007 -0800
-@@ -1370,7 +1370,7 @@
- 
-     // Ensure that there are no instructions between the PHI and the load that
-     // could store.
--    for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
-+    for (BasicBlock::iterator BBI(PN); &*BBI != LI; ++BBI)
-       if (BBI->mayWriteToMemory())
-         return false;
- 
-@@ -2607,7 +2607,8 @@
-                  DL.getTypeStoreSizeInBits(LI.getType()) &&
-              "Non-byte-multiple bit width");
-       // Move the insertion point just past the load so that we can refer to it.
--      IRB.SetInsertPoint(std::next(BasicBlock::iterator(&LI)));
-+      IRB.SetInsertPoint(&*std::next(BasicBlock::iterator(&LI)));
-+
-       // Create a placeholder value with the same type as LI to use as the
-       // basis for the new value. This allows us to replace the uses of LI with
-       // the computed value, and then replace the placeholder with LI, leaving
-@@ -3069,7 +3070,7 @@
-     // dominate the PHI.
-     IRBuilderTy PtrBuilder(IRB);
-     if (isa<PHINode>(OldPtr))
--      PtrBuilder.SetInsertPoint(OldPtr->getParent()->getFirstInsertionPt());
-+      PtrBuilder.SetInsertPoint(&*OldPtr->getParent()->getFirstInsertionPt());
-     else
-       PtrBuilder.SetInsertPoint(OldPtr);
-     PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
-@@ -3714,7 +3715,7 @@
-            "Cannot represent alloca access size using 64-bit integers!");
- 
-     Instruction *BasePtr = cast<Instruction>(LI->getPointerOperand());
--    IRB.SetInsertPoint(BasicBlock::iterator(LI));
-+    IRB.SetInsertPoint(LI);
- 
-     DEBUG(dbgs() << "  Splitting load: " << *LI << "\n");
- 
-@@ -3766,7 +3767,7 @@
-       }
- 
-       Value *StoreBasePtr = SI->getPointerOperand();
--      IRB.SetInsertPoint(BasicBlock::iterator(SI));
-+      IRB.SetInsertPoint(SI);
- 
-       DEBUG(dbgs() << "    Splitting store of load: " << *SI << "\n");
- 
-@@ -3855,7 +3856,7 @@
-       if (SplitLoads) {
-         PLoad = (*SplitLoads)[Idx];
-       } else {
--        IRB.SetInsertPoint(BasicBlock::iterator(LI));
-+        IRB.SetInsertPoint(LI);
-         PLoad = IRB.CreateAlignedLoad(
-             getAdjustedPtr(IRB, *DL, LoadBasePtr,
-                            APInt(DL->getPointerSizeInBits(), PartOffset),
-@@ -3865,7 +3866,7 @@
-       }
- 
-       // And store this partition.
--      IRB.SetInsertPoint(BasicBlock::iterator(SI));
-+      IRB.SetInsertPoint(SI);
-       StoreInst *PStore = IRB.CreateAlignedStore(
-           PLoad, getAdjustedPtr(IRB, *DL, StoreBasePtr,
-                                 APInt(DL->getPointerSizeInBits(), PartOffset),
---- lib/Transforms/Scalar/SampleProfile.cpp	2014-11-18 23:49:26.000000000 -0800
-+++ lib/Transforms/Scalar/SampleProfile.cpp	2016-01-23 20:40:41.000000000 -0800
-@@ -54,8 +54,10 @@
- 
- // Command line option to specify the file to read samples from. This is
- // mainly used for debugging.
--static cl::opt<std::string> SampleProfileFile(
--    "sample-profile-file", cl::init(""), cl::value_desc("filename"),
-+static std::string EmptyInitString("");
-+static cl::opt<std::string>
-+SampleProfileFile("sample-profile-file", cl::init(EmptyInitString),
-+    cl::value_desc("filename"),
-     cl::desc("Profile file loaded by -sample-profile"), cl::Hidden);
- static cl::opt<unsigned> SampleProfileMaxPropagateIterations(
-     "sample-profile-max-propagate-iterations", cl::init(100),
---- lib/Transforms/Scalar/ScalarReplAggregates.cpp	2015-01-04 04:03:27.000000000 -0800
-+++ lib/Transforms/Scalar/ScalarReplAggregates.cpp	2015-11-28 18:31:24.445308022 -0800
-@@ -382,8 +382,9 @@
-     // Create and insert the integer alloca.
-     NewTy = IntegerType::get(AI->getContext(), BitWidth);
-   }
-+
-   AllocaInst *NewAI = new AllocaInst(NewTy, nullptr, "",
--                                     AI->getParent()->begin());
-+                                     &AI->getParent()->front());
-   ConvertUsesToScalar(AI, NewAI, 0, nullptr);
-   return NewAI;
- }
-@@ -1202,7 +1203,7 @@
- 
-     // Ensure that there are no instructions between the PHI and the load that
-     // could store.
--    for (BasicBlock::iterator BBI = PN; &*BBI != LI; ++BBI)
-+    for (BasicBlock::iterator BBI(PN); &*BBI != LI; ++BBI)
-       if (BBI->mayWriteToMemory())
-         return false;
- 
---- lib/Transforms/Scalar/Scalarizer.cpp	2014-11-11 13:30:22.000000000 -0800
-+++ lib/Transforms/Scalar/Scalarizer.cpp	2015-11-29 08:58:18.947961675 -0800
-@@ -250,10 +250,9 @@
- bool Scalarizer::runOnFunction(Function &F) {
-   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
-   DL = DLP ? &DLP->getDataLayout() : nullptr;
--  for (Function::iterator BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
--    BasicBlock *BB = BBI;
--    for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;) {
--      Instruction *I = II;
-+  for (BasicBlock &BB : F) {
-+    for (BasicBlock::iterator II = BB.begin(), IE = BB.end(); II != IE;) {
-+      Instruction *I = &*II;
-       bool Done = visit(I);
-       ++II;
-       if (Done && I->getType()->isVoidTy())
-@@ -282,7 +281,7 @@
-   }
-   // In the fallback case, just put the scattered before Point and
-   // keep the result local to Point.
--  return Scatterer(Point->getParent(), Point, V);
-+  return Scatterer(Point->getParent(), Point->getIterator(), V);
- }
- 
- // Replace Op with the gathered form of the components in CV.  Defer the
-@@ -377,7 +376,7 @@
-     return false;
- 
-   unsigned NumElems = VT->getNumElements();
--  IRBuilder<> Builder(I.getParent(), &I);
-+  IRBuilder<> Builder(&I);
-   Scatterer Op0 = scatter(&I, I.getOperand(0));
-   Scatterer Op1 = scatter(&I, I.getOperand(1));
-   assert(Op0.size() == NumElems && "Mismatched binary operation");
-@@ -397,7 +396,7 @@
-     return false;
- 
-   unsigned NumElems = VT->getNumElements();
--  IRBuilder<> Builder(SI.getParent(), &SI);
-+  IRBuilder<> Builder(&SI);
-   Scatterer Op1 = scatter(&SI, SI.getOperand(1));
-   Scatterer Op2 = scatter(&SI, SI.getOperand(2));
-   assert(Op1.size() == NumElems && "Mismatched select");
-@@ -438,7 +437,7 @@
-   if (!VT)
-     return false;
- 
--  IRBuilder<> Builder(GEPI.getParent(), &GEPI);
-+  IRBuilder<> Builder(&GEPI);
-   unsigned NumElems = VT->getNumElements();
-   unsigned NumIndices = GEPI.getNumIndices();
- 
-@@ -472,7 +471,7 @@
-     return false;
- 
-   unsigned NumElems = VT->getNumElements();
--  IRBuilder<> Builder(CI.getParent(), &CI);
-+  IRBuilder<> Builder(&CI);
-   Scatterer Op0 = scatter(&CI, CI.getOperand(0));
-   assert(Op0.size() == NumElems && "Mismatched cast");
-   ValueVector Res;
-@@ -492,7 +491,7 @@
- 
-   unsigned DstNumElems = DstVT->getNumElements();
-   unsigned SrcNumElems = SrcVT->getNumElements();
--  IRBuilder<> Builder(BCI.getParent(), &BCI);
-+  IRBuilder<> Builder(&BCI);
-   Scatterer Op0 = scatter(&BCI, BCI.getOperand(0));
-   ValueVector Res;
-   Res.resize(DstNumElems);
-@@ -569,7 +568,7 @@
-     return false;
- 
-   unsigned NumElems = VT->getNumElements();
--  IRBuilder<> Builder(PHI.getParent(), &PHI);
-+  IRBuilder<> Builder(&PHI);
-   ValueVector Res;
-   Res.resize(NumElems);
- 
-@@ -599,7 +598,7 @@
-     return false;
- 
-   unsigned NumElems = Layout.VecTy->getNumElements();
--  IRBuilder<> Builder(LI.getParent(), &LI);
-+  IRBuilder<> Builder(&LI);
-   Scatterer Ptr = scatter(&LI, LI.getPointerOperand());
-   ValueVector Res;
-   Res.resize(NumElems);
-@@ -623,7 +622,7 @@
-     return false;
- 
-   unsigned NumElems = Layout.VecTy->getNumElements();
--  IRBuilder<> Builder(SI.getParent(), &SI);
-+  IRBuilder<> Builder(&SI);
-   Scatterer Ptr = scatter(&SI, SI.getPointerOperand());
-   Scatterer Val = scatter(&SI, FullValue);
- 
-@@ -653,7 +652,7 @@
-       Value *Res = UndefValue::get(Ty);
-       BasicBlock *BB = Op->getParent();
-       unsigned Count = Ty->getVectorNumElements();
--      IRBuilder<> Builder(BB, Op);
-+      IRBuilder<> Builder(Op);
-       if (isa<PHINode>(Op))
-         Builder.SetInsertPoint(BB, BB->getFirstInsertionPt());
-       for (unsigned I = 0; I < Count; ++I)
---- lib/Transforms/Scalar/SimplifyCFGPass.cpp	2015-01-04 04:03:27.000000000 -0800
-+++ lib/Transforms/Scalar/SimplifyCFGPass.cpp	2015-11-28 19:16:00.355459043 -0800
-@@ -96,7 +96,7 @@
-     // single PHI node that is the operand to the return.
-     if (Ret != &BB.front()) {
-       // Check for something else in the block.
--      BasicBlock::iterator I = Ret;
-+      BasicBlock::iterator I(Ret);
-       --I;
-       // Skip over debug info.
-       while (isa<DbgInfoIntrinsic>(I) && I != BB.begin())
-@@ -104,7 +104,7 @@
-       if (!isa<DbgInfoIntrinsic>(I) &&
-           (!isa<PHINode>(I) || I != BB.begin() ||
-            Ret->getNumOperands() == 0 ||
--           Ret->getOperand(0) != I))
-+           Ret->getOperand(0) != &*I))
-         continue;
-     }
- 
-@@ -166,7 +166,7 @@
-     // Loop over all of the basic blocks and remove them if they are unneeded...
-     //
-     for (Function::iterator BBIt = F.begin(); BBIt != F.end(); ) {
--      if (SimplifyCFG(BBIt++, TTI, BonusInstThreshold, DL, AC)) {
-+      if (SimplifyCFG(&*BBIt++, TTI, BonusInstThreshold, DL, AC)) {
-         LocalChange = true;
-         ++NumSimpl;
-       }
---- lib/Transforms/Scalar/Sink.cpp	2014-08-24 16:23:06.000000000 -0700
-+++ lib/Transforms/Scalar/Sink.cpp	2015-11-28 19:17:12.178518993 -0800
-@@ -136,7 +136,7 @@
-   bool ProcessedBegin = false;
-   SmallPtrSet<Instruction *, 8> Stores;
-   do {
--    Instruction *Inst = I;  // The instruction to sink.
-+    Instruction *Inst = &*I;  // The instruction to sink.
- 
-     // Predecrement I (if it's not begin) so that it isn't invalidated by
-     // sinking.
-@@ -274,6 +274,6 @@
-         dbgs() << ")\n");
- 
-   // Move the instruction.
--  Inst->moveBefore(SuccToSinkTo->getFirstInsertionPt());
-+  Inst->moveBefore(&*SuccToSinkTo->getFirstInsertionPt());
-   return true;
- }
---- lib/Transforms/Scalar/StructurizeCFG.cpp	2014-12-02 20:28:32.000000000 -0800
-+++ lib/Transforms/Scalar/StructurizeCFG.cpp	2015-11-28 19:23:41.808228788 -0800
-@@ -842,14 +842,14 @@
-             continue;
-         }
- 
--        if (DT->dominates(II, User))
-+        if (DT->dominates(&*II, User))
-           continue;
- 
-         if (!Initialized) {
-           Value *Undef = UndefValue::get(II->getType());
-           Updater.Initialize(II->getType(), "");
-           Updater.AddAvailableValue(&Func->getEntryBlock(), Undef);
--          Updater.AddAvailableValue(BB, II);
-+          Updater.AddAvailableValue(BB, &*II);
-           Initialized = true;
-         }
-         Updater.RewriteUseAfterInsertions(U);
---- lib/Transforms/Scalar/TailRecursionElimination.cpp	2014-11-19 05:32:51.000000000 -0800
-+++ lib/Transforms/Scalar/TailRecursionElimination.cpp	2015-11-28 19:32:29.223858053 -0800
-@@ -404,28 +404,22 @@
-   // alloca' is changed from being a static alloca to being a dynamic alloca.
-   // Until this is resolved, disable this transformation if that would ever
-   // happen.  This bug is PR962.
--  SmallVector<BasicBlock*, 8> BBToErase;
--  for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
-+  for (Function::iterator BBI = F.begin(), E = F.end(); BBI != E;
-+       /* inside loop */) {
-+    BasicBlock *BB = &*BBI;
-+    ++BBI;
-+
-     if (ReturnInst *Ret = dyn_cast<ReturnInst>(BB->getTerminator())) {
-       bool Change = ProcessReturningBlock(Ret, OldEntry, TailCallsAreMarkedTail,
-                                           ArgumentPHIs, !CanTRETailMarkedCall);
--      if (!Change && BB->getFirstNonPHIOrDbg() == Ret) {
-+      if (!Change && BB->getFirstNonPHIOrDbg() == Ret)
-         Change = FoldReturnAndProcessPred(BB, Ret, OldEntry,
-                                           TailCallsAreMarkedTail, ArgumentPHIs,
-                                           !CanTRETailMarkedCall);
--        // FoldReturnAndProcessPred may have emptied some BB. Remember to
--        // erase them.
--        if (Change && BB->empty())
--          BBToErase.push_back(BB);
--
--      }
-       MadeChange |= Change;
-     }
-   }
- 
--  for (auto BB: BBToErase)
--    BB->eraseFromParent();
--
-   // If we eliminated any tail recursions, it's possible that we inserted some
-   // silly PHI nodes which just merge an initial value (the incoming operand)
-   // with themselves.  Check to see if we did and clean up our mess if so.  This
-@@ -588,7 +582,7 @@
-   // Scan backwards from the return, checking to see if there is a tail call in
-   // this block.  If so, set CI to it.
-   CallInst *CI = nullptr;
--  BasicBlock::iterator BBI = TI;
-+  BasicBlock::iterator BBI(TI);
-   while (true) {
-     CI = dyn_cast<CallInst>(BBI);
-     if (CI && CI->getCalledFunction() == F)
-@@ -609,9 +603,8 @@
-   // and disable this xform in this case, because the code generator will
-   // lower the call to fabs into inline code.
-   if (BB == &F->getEntryBlock() &&
--      FirstNonDbg(BB->front()) == CI &&
--      FirstNonDbg(std::next(BB->begin())) == TI &&
--      CI->getCalledFunction() &&
-+      FirstNonDbg(BB->front().getIterator()) == CI &&
-+      FirstNonDbg(std::next(BB->begin())) == TI && CI->getCalledFunction() &&
-       !TTI->isLoweredToCall(CI->getCalledFunction())) {
-     // A single-block function with just a call and a return. Check that
-     // the arguments match.
-@@ -650,19 +643,19 @@
-   // tail call if all of the instructions between the call and the return are
-   // movable to above the call itself, leaving the call next to the return.
-   // Check that this is the case now.
--  BasicBlock::iterator BBI = CI;
-+  BasicBlock::iterator BBI(CI);
-   for (++BBI; &*BBI != Ret; ++BBI) {
--    if (CanMoveAboveCall(BBI, CI)) continue;
-+    if (CanMoveAboveCall(&*BBI, CI)) continue;
- 
-     // If we can't move the instruction above the call, it might be because it
-     // is an associative and commutative operation that could be transformed
-     // using accumulator recursion elimination.  Check to see if this is the
-     // case, and if so, remember the initial accumulator value for later.
-     if ((AccumulatorRecursionEliminationInitVal =
--                           CanTransformAccumulatorRecursion(BBI, CI))) {
-+             CanTransformAccumulatorRecursion(&*BBI, CI))) {
-       // Yes, this is accumulator recursion.  Remember which instruction
-       // accumulates.
--      AccumulatorRecursionInstr = BBI;
-+      AccumulatorRecursionInstr = &*BBI;
-     } else {
-       return false;   // Otherwise, we cannot eliminate the tail recursion!
-     }
-@@ -712,19 +705,19 @@
-              NEBI = NewEntry->begin(); OEBI != E; )
-         if (AllocaInst *AI = dyn_cast<AllocaInst>(OEBI++))
-           if (isa<ConstantInt>(AI->getArraySize()))
--            AI->moveBefore(NEBI);
-+            AI->moveBefore(&*NEBI);
- 
-     // Now that we have created a new block, which jumps to the entry
-     // block, insert a PHI node for each argument of the function.
-     // For now, we initialize each PHI to only have the real arguments
-     // which are passed in.
--    Instruction *InsertPos = OldEntry->begin();
-+    Instruction *InsertPos = &OldEntry->front();
-     for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
-          I != E; ++I) {
-       PHINode *PN = PHINode::Create(I->getType(), 2,
-                                     I->getName() + ".tr", InsertPos);
-       I->replaceAllUsesWith(PN); // Everyone use the PHI node now!
--      PN->addIncoming(I, NewEntry);
-+      PN->addIncoming(&*I, NewEntry);
-       ArgumentPHIs.push_back(PN);
-     }
-   }
-@@ -753,10 +746,9 @@
-     Instruction *AccRecInstr = AccumulatorRecursionInstr;
-     // Start by inserting a new PHI node for the accumulator.
-     pred_iterator PB = pred_begin(OldEntry), PE = pred_end(OldEntry);
--    PHINode *AccPN =
--      PHINode::Create(AccumulatorRecursionEliminationInitVal->getType(),
--                      std::distance(PB, PE) + 1,
--                      "accumulator.tr", OldEntry->begin());
-+    PHINode *AccPN = PHINode::Create(
-+        AccumulatorRecursionEliminationInitVal->getType(),
-+        std::distance(PB, PE) + 1, "accumulator.tr", &OldEntry->front());
- 
-     // Loop over all of the predecessors of the tail recursion block.  For the
-     // real entry into the function we seed the PHI with the initial value,
---- lib/Transforms/Utils/AddDiscriminators.cpp	2014-12-09 10:38:53.000000000 -0800
-+++ lib/Transforms/Utils/AddDiscriminators.cpp	2015-11-29 09:01:43.033905645 -0800
-@@ -172,7 +172,7 @@
-   // Traverse all the blocks looking for instructions in different
-   // blocks that are at the same file:line location.
-   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
--    BasicBlock *B = I;
-+    BasicBlock *B = &*I;
-     TerminatorInst *Last = B->getTerminator();
-     DebugLoc LastLoc = Last->getDebugLoc();
-     if (LastLoc.isUnknown()) continue;
---- lib/Transforms/Utils/BasicBlockUtils.cpp	2014-11-18 16:17:31.000000000 -0800
-+++ lib/Transforms/Utils/BasicBlockUtils.cpp	2015-11-29 09:05:35.763274502 -0800
-@@ -255,7 +255,7 @@
-     // block.
-     assert(SP == BB && "CFG broken");
-     SP = nullptr;
--    return SplitBlock(Succ, Succ->begin(), P);
-+    return SplitBlock(Succ, &Succ->front(), P);
-   }
- 
-   // Otherwise, if BB has a single successor, split it at the bottom of the
-@@ -283,7 +283,7 @@
- /// the loop info is updated.
- ///
- BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) {
--  BasicBlock::iterator SplitIt = SplitPt;
-+  BasicBlock::iterator SplitIt = SplitPt->getIterator();
-   while (isa<PHINode>(SplitIt) || isa<LandingPadInst>(SplitIt))
-     ++SplitIt;
-   BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
-@@ -642,7 +642,7 @@
-       // return instruction.
-       V = BCI->getOperand(0);
-       NewBC = BCI->clone();
--      Pred->getInstList().insert(NewRet, NewBC);
-+      Pred->getInstList().insert(NewRet->getIterator(), NewBC);
-       *i = NewBC;
-     }
-     if (PHINode *PN = dyn_cast<PHINode>(V)) {
-@@ -688,7 +688,7 @@
-                                                 MDNode *BranchWeights,
-                                                 DominatorTree *DT) {
-   BasicBlock *Head = SplitBefore->getParent();
--  BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
-+  BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator());
-   TerminatorInst *HeadOldTerm = Head->getTerminator();
-   LLVMContext &C = Head->getContext();
-   BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
-@@ -739,7 +739,7 @@
-                                          TerminatorInst **ElseTerm,
-                                          MDNode *BranchWeights) {
-   BasicBlock *Head = SplitBefore->getParent();
--  BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
-+  BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator());
-   TerminatorInst *HeadOldTerm = Head->getTerminator();
-   LLVMContext &C = Head->getContext();
-   BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
---- lib/Transforms/Utils/BreakCriticalEdges.cpp	2014-11-18 16:17:31.000000000 -0800
-+++ lib/Transforms/Utils/BreakCriticalEdges.cpp	2015-11-29 09:07:57.703524612 -0800
-@@ -98,7 +98,7 @@
-     PHINode *NewPN =
-       PHINode::Create(PN->getType(), Preds.size(), "split",
-                       SplitBB->isLandingPad() ?
--                      SplitBB->begin() : SplitBB->getTerminator());
-+                      &SplitBB->front() : SplitBB->getTerminator());
-     for (unsigned i = 0, e = Preds.size(); i != e; ++i)
-       NewPN->addIncoming(V, Preds[i]);
- 
-@@ -152,7 +152,7 @@
- 
-   // Insert the block into the function... right after the block TI lives in.
-   Function &F = *TIBB->getParent();
--  Function::iterator FBBI = TIBB;
-+  Function::iterator FBBI = TIBB->getIterator();
-   F.getBasicBlockList().insert(++FBBI, NewBB);
- 
-   // If there are any PHI nodes in DestBB, we need to update them so that they
---- lib/Transforms/Utils/BypassSlowDivision.cpp	2014-04-24 22:29:35.000000000 -0700
-+++ lib/Transforms/Utils/BypassSlowDivision.cpp	2015-11-29 09:10:30.545799550 -0800
-@@ -82,7 +82,7 @@
-                           bool UseSignedOp,
-                           DivCacheTy &PerBBDivCache) {
-   // Get instruction operands
--  Instruction *Instr = J;
-+  Instruction *Instr = &*J;
-   Value *Dividend = Instr->getOperand(0);
-   Value *Divisor = Instr->getOperand(1);
- 
-@@ -94,7 +94,7 @@
-   }
- 
-   // Basic Block is split before divide
--  BasicBlock *MainBB = I;
-+  BasicBlock *MainBB = &*I;
-   BasicBlock *SuccessorBB = I->splitBasicBlock(J);
-   ++I; //advance iterator I to successorBB
- 
-@@ -190,7 +190,7 @@
-                                  bool UseSignedOp,
-                                  DivCacheTy &PerBBDivCache) {
-   // Get instruction operands
--  Instruction *Instr = J;
-+  Instruction *Instr = &*J;
-   DivOpInfo Key(UseSignedOp, Instr->getOperand(0), Instr->getOperand(1));
-   DivCacheTy::iterator CacheI = PerBBDivCache.find(Key);
- 
---- lib/Transforms/Utils/CloneFunction.cpp	2014-12-18 22:06:18.000000000 -0800
-+++ lib/Transforms/Utils/CloneFunction.cpp	2015-11-29 09:27:19.893077178 -0800
-@@ -51,7 +51,7 @@
-     if (II->hasName())
-       NewInst->setName(II->getName()+NameSuffix);
-     NewBB->getInstList().push_back(NewInst);
--    VMap[II] = NewInst;                // Add instruction map to value.
-+    VMap[&*II] = NewInst;                // Add instruction map to value.
-     
-     hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
-     if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
-@@ -86,7 +86,7 @@
- #ifndef NDEBUG
-   for (Function::const_arg_iterator I = OldFunc->arg_begin(), 
-        E = OldFunc->arg_end(); I != E; ++I)
--    assert(VMap.count(I) && "No mapping from source argument specified!");
-+    assert(VMap.count(&*I) && "No mapping from source argument specified!");
- #endif
- 
-   // Copy all attributes other than those stored in the AttributeSet.  We need
-@@ -145,11 +145,12 @@
- 
-   // Loop over all of the instructions in the function, fixing up operand
-   // references as we go.  This uses VMap to do all the hard work.
--  for (Function::iterator BB = cast<BasicBlock>(VMap[OldFunc->begin()]),
--         BE = NewFunc->end(); BB != BE; ++BB)
-+  for (Function::iterator BB =
-+       cast<BasicBlock>(VMap[&OldFunc->front()])->getIterator(),
-+       BE = NewFunc->end(); BB != BE; ++BB)
-     // Loop over all instructions, fixing each one as we find it...
--    for (BasicBlock::iterator II = BB->begin(); II != BB->end(); ++II)
--      RemapInstruction(II, VMap,
-+    for (Instruction &II : *BB)
-+      RemapInstruction(&II, VMap,
-                        ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges,
-                        TypeMapper, Materializer);
- }
-@@ -220,7 +221,7 @@
-   //
-   for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
-        I != E; ++I)
--    if (VMap.count(I) == 0)  // Haven't mapped the argument to anything yet?
-+    if (VMap.count(&*I) == 0)  // Haven't mapped the argument to anything yet?
-       ArgTypes.push_back(I->getType());
- 
-   // Create a new function type...
-@@ -234,9 +235,9 @@
-   Function::arg_iterator DestI = NewF->arg_begin();
-   for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
-        I != E; ++I)
--    if (VMap.count(I) == 0) {   // Is this argument preserved?
--      DestI->setName(I->getName()); // Copy the name over...
--      VMap[I] = DestI++;        // Add mapping to VMap
-+    if (VMap.count(&*I) == 0) {       // Is this argument preserved?
-+      DestI->setName(I->getName());   // Copy the name over...
-+      VMap[&*I] = &*DestI++;          // Add mapping to VMap
-     }
- 
-   if (ModuleLevelChanges)
-@@ -332,7 +333,7 @@
-         if (Value *MappedV = VMap.lookup(V))
-           V = MappedV;
- 
--        VMap[II] = V;
-+        VMap[&*II] = V;
-         delete NewInst;
-         continue;
-       }
-@@ -340,9 +341,10 @@
- 
-     if (II->hasName())
-       NewInst->setName(II->getName()+NameSuffix);
--    VMap[II] = NewInst;                // Add instruction map to value.
-+    VMap[&*II] = NewInst;                // Add instruction map to value.
-     NewBB->getInstList().push_back(NewInst);
-     hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
-+
-     if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
-       if (isa<ConstantInt>(AI->getArraySize()))
-         hasStaticAllocas = true;
-@@ -429,7 +431,7 @@
- #ifndef NDEBUG
-   for (Function::const_arg_iterator II = OldFunc->arg_begin(), 
-        E = OldFunc->arg_end(); II != E; ++II)
--    assert(VMap.count(II) && "No mapping from source argument specified!");
-+    assert(VMap.count(&*II) && "No mapping from source argument specified!");
- #endif
- 
-   PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges,
-@@ -452,7 +454,7 @@
-   SmallVector<const PHINode*, 16> PHIToResolve;
-   for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
-        BI != BE; ++BI) {
--    Value *V = VMap[BI];
-+    Value *V = VMap[&*BI];
-     BasicBlock *NewBB = cast_or_null<BasicBlock>(V);
-     if (!NewBB) continue;  // Dead block.
- 
-@@ -546,8 +548,8 @@
-       while ((PN = dyn_cast<PHINode>(I++))) {
-         Value *NV = UndefValue::get(PN->getType());
-         PN->replaceAllUsesWith(NV);
--        assert(VMap[OldI] == PN && "VMap mismatch");
--        VMap[OldI] = NV;
-+        assert(VMap[&*OldI] == PN && "VMap mismatch");
-+        VMap[&*OldI] = NV;
-         PN->eraseFromParent();
-         ++OldI;
-       }
-@@ -569,15 +571,16 @@
-   // and zap unconditional fall-through branches.  This happen all the time when
-   // specializing code: code specialization turns conditional branches into
-   // uncond branches, and this code folds them.
--  Function::iterator Begin = cast<BasicBlock>(VMap[&OldFunc->getEntryBlock()]);
-+  Function::iterator Begin =
-+    cast<BasicBlock>(VMap[&OldFunc->getEntryBlock()])->getIterator();
-   Function::iterator I = Begin;
-   while (I != NewFunc->end()) {
-     // Check if this block has become dead during inlining or other
-     // simplifications. Note that the first block will appear dead, as it has
-     // not yet been wired up properly.
--    if (I != Begin && (pred_begin(I) == pred_end(I) ||
--                       I->getSinglePredecessor() == I)) {
--      BasicBlock *DeadBB = I++;
-+    if ((I != Begin) && (pred_begin(&*I) == pred_end(&*I) ||
-+                         I->getSinglePredecessor() == &*I)) {
-+      BasicBlock *DeadBB = &*I++;
-       DeleteDeadBlock(DeadBB);
-       continue;
-     }
-@@ -587,7 +590,7 @@
-     // simplification required looking through PHI nodes, those are only
-     // available after forming the full basic block. That may leave some here,
-     // and we still want to prune the dead code as early as possible.
--    ConstantFoldTerminator(I);
-+    ConstantFoldTerminator(&*I);
- 
-     BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator());
-     if (!BI || BI->isConditional()) { ++I; continue; }
-@@ -606,7 +609,7 @@
-     BI->eraseFromParent();
-     
-     // Make all PHI nodes that referred to Dest now refer to I as their source.
--    Dest->replaceAllUsesWith(I);
-+    Dest->replaceAllUsesWith(&*I);
- 
-     // Move all the instructions in the succ to the pred.
-     I->getInstList().splice(I->end(), Dest->getInstList());
-@@ -620,9 +623,9 @@
-   // Make a final pass over the basic blocks from theh old function to gather
-   // any return instructions which survived folding. We have to do this here
-   // because we can iteratively remove and merge returns above.
--  for (Function::iterator I = cast<BasicBlock>(VMap[&OldFunc->getEntryBlock()]),
--                          E = NewFunc->end();
--       I != E; ++I)
-+  for (Function::iterator I =
-+       cast<BasicBlock>(VMap[&OldFunc->getEntryBlock()])->getIterator(),
-+       E = NewFunc->end(); I != E; ++I)
-     if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator()))
-       Returns.push_back(RI);
- }
---- lib/Transforms/Utils/CloneModule.cpp	2014-12-23 00:23:45.000000000 -0800
-+++ lib/Transforms/Utils/CloneModule.cpp	2015-11-29 10:05:42.438731638 -0800
-@@ -45,15 +45,15 @@
-   //
-   for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
-        I != E; ++I) {
--    GlobalVariable *GV = new GlobalVariable(*New, 
-+    GlobalVariable *GV = new GlobalVariable(*New,
-                                             I->getType()->getElementType(),
-                                             I->isConstant(), I->getLinkage(),
-                                             (Constant*) nullptr, I->getName(),
-                                             (GlobalVariable*) nullptr,
-                                             I->getThreadLocalMode(),
-                                             I->getType()->getAddressSpace());
--    GV->copyAttributesFrom(I);
--    VMap[I] = GV;
-+    GV->copyAttributesFrom(&*I);
-+    VMap[&*I] = GV;
-   }
- 
-   // Loop over the functions in the module, making external functions as before
-@@ -61,8 +61,8 @@
-     Function *NF =
-       Function::Create(cast<FunctionType>(I->getType()->getElementType()),
-                        I->getLinkage(), I->getName(), New);
--    NF->copyAttributesFrom(I);
--    VMap[I] = NF;
-+    NF->copyAttributesFrom(&*I);
-+    VMap[&*I] = NF;
-   }
- 
-   // Loop over the aliases in the module
-@@ -72,8 +72,8 @@
-     auto *GA =
-         GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
-                             I->getLinkage(), I->getName(), New);
--    GA->copyAttributesFrom(I);
--    VMap[I] = GA;
-+    GA->copyAttributesFrom(&*I);
-+    VMap[&*I] = GA;
-   }
-   
-   // Now that all of the things that global variable initializer can refer to
-@@ -82,7 +82,7 @@
-   //
-   for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
-        I != E; ++I) {
--    GlobalVariable *GV = cast<GlobalVariable>(VMap[I]);
-+    GlobalVariable *GV = cast<GlobalVariable>(VMap[&*I]);
-     if (I->hasInitializer())
-       GV->setInitializer(MapValue(I->getInitializer(), VMap));
-   }
-@@ -90,24 +90,24 @@
-   // Similarly, copy over function bodies now...
-   //
-   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) {
--    Function *F = cast<Function>(VMap[I]);
-+    Function *F = cast<Function>(VMap[&*I]);
-     if (!I->isDeclaration()) {
-       Function::arg_iterator DestI = F->arg_begin();
-       for (Function::const_arg_iterator J = I->arg_begin(); J != I->arg_end();
-            ++J) {
-         DestI->setName(J->getName());
--        VMap[J] = DestI++;
-+        VMap[&*J] = &*DestI++;
-       }
- 
-       SmallVector<ReturnInst*, 8> Returns;  // Ignore returns cloned.
--      CloneFunctionInto(F, I, VMap, /*ModuleLevelChanges=*/true, Returns);
-+      CloneFunctionInto(F, &*I, VMap, /*ModuleLevelChanges=*/true, Returns);
-     }
-   }
- 
-   // And aliases
-   for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
-        I != E; ++I) {
--    GlobalAlias *GA = cast<GlobalAlias>(VMap[I]);
-+    GlobalAlias *GA = cast<GlobalAlias>(VMap[&*I]);
-     if (const Constant *C = I->getAliasee())
-       GA->setAliasee(MapValue(C, VMap));
-   }
---- lib/Transforms/Utils/CodeExtractor.cpp	2014-07-21 10:06:51.000000000 -0700
-+++ lib/Transforms/Utils/CodeExtractor.cpp	2015-11-29 10:25:40.506775548 -0800
-@@ -175,7 +175,7 @@
- 
-       for (User *U : II->users())
-         if (!definedInRegion(Blocks, U)) {
--          Outputs.insert(II);
-+          Outputs.insert(&*II);
-           break;
-         }
-     }
-@@ -211,7 +211,7 @@
-   // containing PHI nodes merging values from outside of the region, and a
-   // second that contains all of the code for the block and merges back any
-   // incoming values from inside of the region.
--  BasicBlock::iterator AfterPHIs = Header->getFirstNonPHI();
-+  BasicBlock::iterator AfterPHIs = Header->getFirstNonPHI()->getIterator();
-   BasicBlock *NewBB = Header->splitBasicBlock(AfterPHIs,
-                                               Header->getName()+".ce");
- 
-@@ -246,7 +246,7 @@
-       // Create a new PHI node in the new region, which has an incoming value
-       // from OldPred of PN.
-       PHINode *NewPN = PHINode::Create(PN->getType(), 1 + NumPredsFromRegion,
--                                       PN->getName()+".ce", NewBB->begin());
-+                                       PN->getName()+".ce", &NewBB->front());
-       NewPN->addIncoming(PN, OldPred);
- 
-       // Loop over all of the incoming value in PN, moving them to NewPN if they
-@@ -266,14 +266,15 @@
-   for (SetVector<BasicBlock *>::iterator I = Blocks.begin(), E = Blocks.end();
-        I != E; ++I)
-     if (ReturnInst *RI = dyn_cast<ReturnInst>((*I)->getTerminator())) {
--      BasicBlock *New = (*I)->splitBasicBlock(RI, (*I)->getName()+".ret");
-+      BasicBlock *New =
-+        (*I)->splitBasicBlock(RI->getIterator(), (*I)->getName() + ".ret");
-       if (DT) {
-         // Old dominates New. New node dominates all other nodes dominated
-         // by Old.
-         DomTreeNode *OldNode = DT->getNode(*I);
-         SmallVector<DomTreeNode*, 8> Children;
-         for (DomTreeNode::iterator DI = OldNode->begin(), DE = OldNode->end();
--             DI != DE; ++DI) 
-+             DI != DE; ++DI)
-           Children.push_back(*DI);
- 
-         DomTreeNode *NewNode = DT->addNewBlock(New, *I);
-@@ -364,11 +365,11 @@
-       Idx[0] = Constant::getNullValue(Type::getInt32Ty(header->getContext()));
-       Idx[1] = ConstantInt::get(Type::getInt32Ty(header->getContext()), i);
-       TerminatorInst *TI = newFunction->begin()->getTerminator();
--      GetElementPtrInst *GEP = 
--        GetElementPtrInst::Create(AI, Idx, "gep_" + inputs[i]->getName(), TI);
-+      GetElementPtrInst *GEP =
-+        GetElementPtrInst::Create(&*AI, Idx, "gep_" + inputs[i]->getName(), TI);
-       RewriteVal = new LoadInst(GEP, "loadgep_" + inputs[i]->getName(), TI);
-     } else
--      RewriteVal = AI++;
-+      RewriteVal = &*AI++;
- 
-     std::vector<User*> Users(inputs[i]->user_begin(), inputs[i]->user_end());
-     for (std::vector<User*>::iterator use = Users.begin(), useE = Users.end();
-@@ -441,7 +442,7 @@
-     } else {
-       AllocaInst *alloca =
-         new AllocaInst((*i)->getType(), nullptr, (*i)->getName()+".loc",
--                       codeReplacer->getParent()->begin()->begin());
-+                       &codeReplacer->getParent()->front().front());
-       ReloadOutputs.push_back(alloca);
-       params.push_back(alloca);
-     }
-@@ -458,7 +459,7 @@
-     Type *StructArgTy = StructType::get(newFunction->getContext(), ArgTypes);
-     Struct =
-       new AllocaInst(StructArgTy, nullptr, "structArg",
--                     codeReplacer->getParent()->begin()->begin());
-+                     &codeReplacer->getParent()->front().front());
-     params.push_back(Struct);
- 
-     for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
-@@ -607,12 +608,12 @@
-                 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context),
-                                           FirstOut+out);
-                 GetElementPtrInst *GEP =
--                  GetElementPtrInst::Create(OAI, Idx,
-+                  GetElementPtrInst::Create(&*OAI, Idx,
-                                             "gep_" + outputs[out]->getName(),
-                                             NTRet);
-                 new StoreInst(outputs[out], GEP, NTRet);
-               } else {
--                new StoreInst(outputs[out], OAI, NTRet);
-+                new StoreInst(outputs[out], &*OAI, NTRet);
-               }
-             }
-             // Advance output iterator even if we don't emit a store
---- lib/Transforms/Utils/CtorUtils.cpp	2014-09-23 15:33:01.000000000 -0700
-+++ lib/Transforms/Utils/CtorUtils.cpp	2015-11-29 10:27:14.531198062 -0800
-@@ -49,7 +49,7 @@
-   GlobalVariable *NGV =
-       new GlobalVariable(CA->getType(), GCL->isConstant(), GCL->getLinkage(),
-                          CA, "", GCL->getThreadLocalMode());
--  GCL->getParent()->getGlobalList().insert(GCL, NGV);
-+  GCL->getParent()->getGlobalList().insert(GCL->getIterator(), NGV);
-   NGV->takeName(GCL);
- 
-   // Nuke the old list, replacing any uses with the new one.
---- lib/Transforms/Utils/DemoteRegToStack.cpp	2014-04-24 22:29:35.000000000 -0700
-+++ lib/Transforms/Utils/DemoteRegToStack.cpp	2015-11-29 10:33:53.846940110 -0800
-@@ -36,7 +36,7 @@
-   } else {
-     Function *F = I.getParent()->getParent();
-     Slot = new AllocaInst(I.getType(), nullptr, I.getName()+".reg2mem",
--                          F->getEntryBlock().begin());
-+                          &F->getEntryBlock().front());
-   }
- 
-   // Change all of the users of the instruction to read from the stack slot.
-@@ -77,30 +77,15 @@
-   // AFTER the terminator instruction.
-   BasicBlock::iterator InsertPt;
-   if (!isa<TerminatorInst>(I)) {
--    InsertPt = &I;
--    ++InsertPt;
-+    InsertPt = ++I.getIterator();
-+    for (; isa<PHINode>(InsertPt) || isa<LandingPadInst>(InsertPt);
-+         ++InsertPt);
-   } else {
-     InvokeInst &II = cast<InvokeInst>(I);
--    if (II.getNormalDest()->getSinglePredecessor())
--      InsertPt = II.getNormalDest()->getFirstInsertionPt();
--    else {
--      // We cannot demote invoke instructions to the stack if their normal edge
--      // is critical.  Therefore, split the critical edge and insert the store
--      // in the newly created basic block.
--      unsigned SuccNum = GetSuccessorNumber(I.getParent(), II.getNormalDest());
--      TerminatorInst *TI = &cast<TerminatorInst>(I);
--      assert (isCriticalEdge(TI, SuccNum) &&
--              "Expected a critical edge!");
--      BasicBlock *BB = SplitCriticalEdge(TI, SuccNum);
--      assert (BB && "Unable to split critical edge.");
--      InsertPt = BB->getFirstInsertionPt();
--    }
-+    InsertPt = II.getNormalDest()->getFirstInsertionPt();
-   }
- 
--  for (; isa<PHINode>(InsertPt) || isa<LandingPadInst>(InsertPt); ++InsertPt)
--    /* empty */;   // Don't insert before PHI nodes or landingpad instrs.
--
--  new StoreInst(&I, Slot, InsertPt);
-+  new StoreInst(&I, Slot, &*InsertPt);
-   return Slot;
- }
- 
-@@ -121,7 +106,7 @@
-   } else {
-     Function *F = P->getParent()->getParent();
-     Slot = new AllocaInst(P->getType(), nullptr, P->getName()+".reg2mem",
--                          F->getEntryBlock().begin());
-+                          &F->getEntryBlock().front());
-   }
- 
-   // Iterate over each operand inserting a store in each predecessor.
-@@ -135,12 +120,12 @@
-   }
- 
-   // Insert a load in place of the PHI and replace all uses.
--  BasicBlock::iterator InsertPt = P;
-+  BasicBlock::iterator InsertPt = P->getIterator();
- 
-   for (; isa<PHINode>(InsertPt) || isa<LandingPadInst>(InsertPt); ++InsertPt)
-     /* empty */;   // Don't insert before PHI nodes or landingpad instrs.
- 
--  Value *V = new LoadInst(Slot, P->getName()+".reload", InsertPt);
-+  Value *V = new LoadInst(Slot, P->getName()+".reload", &*InsertPt);
-   P->replaceAllUsesWith(V);
- 
-   // Delete PHI.
---- lib/Transforms/Utils/FlattenCFG.cpp	2014-08-13 13:31:53.000000000 -0700
-+++ lib/Transforms/Utils/FlattenCFG.cpp	2015-11-29 10:42:20.827355223 -0800
-@@ -177,8 +177,9 @@
- 
-       // Instructions in the internal condition blocks should be safe
-       // to hoist up.
--      for (BasicBlock::iterator BI = Pred->begin(), BE = PBI; BI != BE;) {
--        Instruction *CI = BI++;
-+      for (BasicBlock::iterator BI = Pred->begin(), BE = PBI->getIterator();
-+           BI != BE;) {
-+        Instruction *CI = &*BI++;
-         if (isa<PHINode>(CI) || !isSafeToSpeculativelyExecute(CI))
-           return false;
-       }
-@@ -315,7 +316,7 @@
-                                          BasicBlock *Block1,
-                                          BasicBlock *Block2) {
-   TerminatorInst *PTI2 = Head2->getTerminator();
--  Instruction *PBI2 = Head2->begin();
-+  Instruction *PBI2 = &Head2->front();
- 
-   bool eq1 = (Block1 == Head1);
-   bool eq2 = (Block2 == Head2);
-@@ -327,9 +328,9 @@
-   // Check whether instructions in Block1 and Block2 are identical
-   // and do not alias with instructions in Head2.
-   BasicBlock::iterator iter1 = Block1->begin();
--  BasicBlock::iterator end1 = Block1->getTerminator();
-+  BasicBlock::iterator end1 = Block1->getTerminator()->getIterator();
-   BasicBlock::iterator iter2 = Block2->begin();
--  BasicBlock::iterator end2 = Block2->getTerminator();
-+  BasicBlock::iterator end2 = Block2->getTerminator()->getIterator();
- 
-   while (1) {
-     if (iter1 == end1) {
-@@ -338,7 +339,7 @@
-       break;
-     }
- 
--    if (!iter1->isIdenticalTo(iter2))
-+    if (!iter1->isIdenticalTo(&*iter2))
-       return false;
- 
-     // Illegal to remove instructions with side effects except
-@@ -356,10 +357,10 @@
-       return false;
- 
-     if (iter1->mayWriteToMemory()) {
--      for (BasicBlock::iterator BI = PBI2, BE = PTI2; BI != BE; ++BI) {
-+      for (BasicBlock::iterator BI(PBI2), BE(PTI2); BI != BE; ++BI) {
-         if (BI->mayReadFromMemory() || BI->mayWriteToMemory()) {
-           // Check alias with Head2.
--          if (!AA || AA->alias(iter1, BI))
-+          if (!AA || AA->alias(&*iter1, &*BI))
-             return false;
-         }
-       }
-@@ -413,7 +414,7 @@
-     return false;
- 
-   TerminatorInst *PTI2 = SecondEntryBlock->getTerminator();
--  Instruction *PBI2 = SecondEntryBlock->begin();
-+  Instruction *PBI2 = &SecondEntryBlock->front();
- 
-   if (!CompareIfRegionBlock(FirstEntryBlock, SecondEntryBlock, IfTrue1,
-                             IfTrue2))
-@@ -425,8 +426,8 @@
- 
-   // Check whether \param SecondEntryBlock has side-effect and is safe to
-   // speculate.
--  for (BasicBlock::iterator BI = PBI2, BE = PTI2; BI != BE; ++BI) {
--    Instruction *CI = BI;
-+  for (BasicBlock::iterator BI(PBI2), BE(PTI2); BI != BE; ++BI) {
-+    Instruction *CI = &*BI;
-     if (isa<PHINode>(CI) || CI->mayHaveSideEffects() ||
-         !isSafeToSpeculativelyExecute(CI))
-       return false;
---- lib/Transforms/Utils/InlineFunction.cpp	2015-01-04 04:03:27.000000000 -0800
-+++ lib/Transforms/Utils/InlineFunction.cpp	2015-11-29 12:31:32.233733995 -0800
-@@ -128,7 +128,7 @@
-   if (InnerResumeDest) return InnerResumeDest;
- 
-   // Split the landing pad.
--  BasicBlock::iterator SplitPoint = CallerLPad; ++SplitPoint;
-+  BasicBlock::iterator SplitPoint = ++CallerLPad->getIterator();
-   InnerResumeDest =
-     OuterResumeDest->splitBasicBlock(SplitPoint,
-                                      OuterResumeDest->getName() + ".body");
-@@ -137,7 +137,7 @@
-   const unsigned PHICapacity = 2;
- 
-   // Create corresponding new PHIs for all the PHIs in the outer landing pad.
--  BasicBlock::iterator InsertPoint = InnerResumeDest->begin();
-+  Instruction *InsertPoint = &InnerResumeDest->front();
-   BasicBlock::iterator I = OuterResumeDest->begin();
-   for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
-     PHINode *OuterPHI = cast<PHINode>(I);
-@@ -185,7 +185,8 @@
- static void HandleCallsInBlockInlinedThroughInvoke(BasicBlock *BB,
-                                                    InvokeInliningInfo &Invoke) {
-   for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
--    Instruction *I = BBI++;
-+    Instruction *I = &*BBI;
-+    ++BBI;
- 
-     // We only need to check for function calls: inlined invoke
-     // instructions require no special handling.
-@@ -198,7 +199,8 @@
- 
-     // Convert this function call into an invoke instruction.  First, split the
-     // basic block.
--    BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
-+    BasicBlock *Split =
-+      BB->splitBasicBlock(CI->getIterator(), CI->getName() + ".noexc");
- 
-     // Delete the unconditional branch inserted by splitBasicBlock
-     BB->getInstList().pop_back();
-@@ -246,7 +248,8 @@
- 
-   // Get all of the inlined landing pad instructions.
-   SmallPtrSet<LandingPadInst*, 16> InlinedLPads;
--  for (Function::iterator I = FirstNewBlock, E = Caller->end(); I != E; ++I)
-+  for (Function::iterator I = FirstNewBlock->getIterator(), E = Caller->end();
-+       I != E; ++I)
-     if (InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator()))
-       InlinedLPads.insert(II->getLandingPadInst());
- 
-@@ -262,9 +265,10 @@
-       InlinedLPad->setCleanup(true);
-   }
- 
--  for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E; ++BB){
-+  for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end();
-+       BB != E; ++BB){
-     if (InlinedCodeInfo.ContainsCalls)
--      HandleCallsInBlockInlinedThroughInvoke(BB, Invoke);
-+      HandleCallsInBlockInlinedThroughInvoke(&*BB, Invoke);
- 
-     // Forward any resumes that are remaining here.
-     if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator()))
-@@ -406,10 +410,9 @@
-   const Function *CalledFunc = CS.getCalledFunction();
-   SmallVector<const Argument *, 4> NoAliasArgs;
- 
--  for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
--       E = CalledFunc->arg_end(); I != E; ++I) {
--    if (I->hasNoAliasAttr() && !I->hasNUses(0))
--      NoAliasArgs.push_back(I);
-+  for (const Argument &A : CalledFunc->args()) {
-+    if (A.hasNoAliasAttr() && !A.hasNUses(0))
-+      NoAliasArgs.push_back(&A);
-   }
- 
-   if (NoAliasArgs.empty())
-@@ -727,7 +730,7 @@
-                                     BasicBlock *InsertBlock,
-                                     InlineFunctionInfo &IFI) {
-   Type *AggTy = cast<PointerType>(Src->getType())->getElementType();
--  IRBuilder<> Builder(InsertBlock->begin());
-+  IRBuilder<> Builder(InsertBlock, InsertBlock->begin());
- 
-   Value *Size;
-   if (IFI.DL == nullptr)
-@@ -962,7 +965,7 @@
- 
-   // Get an iterator to the last basic block in the function, which will have
-   // the new function inlined after it.
--  Function::iterator LastBlock = &Caller->back();
-+  Function::iterator LastBlock = --Caller->end();
- 
-   // Make sure to capture all of the return instructions from the cloned
-   // function.
-@@ -997,7 +1000,7 @@
-           ByValInit.push_back(std::make_pair(ActualArg, (Value*) *AI));
-       }
- 
--      VMap[I] = ActualArg;
-+      VMap[&*I] = ActualArg;
-     }
- 
-     // Add alignment assumptions if necessary. We do this before the inlined
-@@ -1014,12 +1017,13 @@
-                               &InlinedFunctionInfo, IFI.DL, TheCall);
- 
-     // Remember the first block that is newly cloned over.
--    FirstNewBlock = LastBlock; ++FirstNewBlock;
-+    FirstNewBlock = LastBlock;
-+    ++FirstNewBlock;
- 
-     // Inject byval arguments initialization.
-     for (std::pair<Value*, Value*> &Init : ByValInit)
-       HandleByValArgumentInit(Init.first, Init.second, Caller->getParent(),
--                              FirstNewBlock, IFI);
-+                              &*FirstNewBlock, IFI);
- 
-     // Update the callgraph if requested.
-     if (IFI.CG)
-@@ -1077,7 +1081,7 @@
-       // reinserted.
-       Caller->getEntryBlock().getInstList().splice(InsertPoint,
-                                                    FirstNewBlock->getInstList(),
--                                                   AI, I);
-+                                                   AI->getIterator(), I);
-     }
-   }
- 
-@@ -1123,7 +1127,7 @@
-   // Leave lifetime markers for the static alloca's, scoping them to the
-   // function we just inlined.
-   if (InsertLifetime && !IFI.StaticAllocas.empty()) {
--    IRBuilder<> builder(FirstNewBlock->begin());
-+    IRBuilder<> builder(&FirstNewBlock->front());
-     for (unsigned ai = 0, ae = IFI.StaticAllocas.size(); ai != ae; ++ai) {
-       AllocaInst *AI = IFI.StaticAllocas[ai];
- 
-@@ -1172,8 +1176,9 @@
-     Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore);
- 
-     // Insert the llvm.stacksave.
--    CallInst *SavedPtr = IRBuilder<>(FirstNewBlock, FirstNewBlock->begin())
--      .CreateCall(StackSave, "savedstack");
-+    CallInst *SavedPtr =
-+      IRBuilder<>(&*FirstNewBlock,
-+                  FirstNewBlock->begin()).CreateCall(StackSave, "savedstack");
- 
-     // Insert a call to llvm.stackrestore before any return instructions in the
-     // inlined function.
-@@ -1189,7 +1194,7 @@
-   // If we are inlining for an invoke instruction, we must make sure to rewrite
-   // any call instructions into invoke instructions.
-   if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
--    HandleInlinedInvoke(II, FirstNewBlock, InlinedFunctionInfo);
-+    HandleInlinedInvoke(II, &*FirstNewBlock, InlinedFunctionInfo);
- 
-   // Handle any inlined musttail call sites.  In order for a new call site to be
-   // musttail, the source of the clone and the inlined call site must have been
-@@ -1233,8 +1238,10 @@
-   // the calling basic block.
-   if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
-     // Move all of the instructions right before the call.
--    OrigBB->getInstList().splice(TheCall, FirstNewBlock->getInstList(),
--                                 FirstNewBlock->begin(), FirstNewBlock->end());
-+    OrigBB->getInstList().splice(TheCall->getIterator(),
-+                                 FirstNewBlock->getInstList(),
-+                                 FirstNewBlock->begin(),
-+                                 FirstNewBlock->end());
-     // Remove the cloned basic block.
-     Caller->getBasicBlockList().pop_back();
- 
-@@ -1280,14 +1287,15 @@
-     // Split the basic block.  This guarantees that no PHI nodes will have to be
-     // updated due to new incoming edges, and make the invoke case more
-     // symmetric to the call case.
--    AfterCallBB = OrigBB->splitBasicBlock(CreatedBranchToNormalDest,
--                                          CalledFunc->getName()+".exit");
-+    AfterCallBB =
-+      OrigBB->splitBasicBlock(CreatedBranchToNormalDest->getIterator(),
-+                              CalledFunc->getName() + ".exit");
- 
-   } else {  // It's a call
-     // If this is a call instruction, we need to split the basic block that
-     // the call lives in.
-     //
--    AfterCallBB = OrigBB->splitBasicBlock(TheCall,
-+    AfterCallBB = OrigBB->splitBasicBlock(TheCall->getIterator(),
-                                           CalledFunc->getName()+".exit");
-   }
- 
-@@ -1297,13 +1305,14 @@
-   TerminatorInst *Br = OrigBB->getTerminator();
-   assert(Br && Br->getOpcode() == Instruction::Br &&
-          "splitBasicBlock broken!");
--  Br->setOperand(0, FirstNewBlock);
-+  Br->setOperand(0, &*FirstNewBlock);
- 
- 
-   // Now that the function is correct, make it a little bit nicer.  In
-   // particular, move the basic blocks inserted from the end of the function
-   // into the space made by splitting the source basic block.
--  Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
-+  Caller->getBasicBlockList().splice(AfterCallBB->getIterator(),
-+                                     Caller->getBasicBlockList(),
-                                      FirstNewBlock, Caller->end());
- 
-   // Handle all of the return instructions that we just cloned in, and eliminate
-@@ -1316,7 +1325,7 @@
-     // possible incoming values.
-     if (!TheCall->use_empty()) {
-       PHI = PHINode::Create(RTy, Returns.size(), TheCall->getName(),
--                            AfterCallBB->begin());
-+                            &AfterCallBB->front());
-       // Anything that used the result of the function call should now use the
-       // PHI node as their operand.
-       TheCall->replaceAllUsesWith(PHI);
-@@ -1396,7 +1405,7 @@
-   // Splice the code entry block into calling block, right before the
-   // unconditional branch.
-   CalleeEntry->replaceAllUsesWith(OrigBB);  // Update PHI nodes
--  OrigBB->getInstList().splice(Br, CalleeEntry->getInstList());
-+  OrigBB->getInstList().splice(Br->getIterator(), CalleeEntry->getInstList());
- 
-   // Remove the unconditional branch.
-   OrigBB->getInstList().erase(Br);
---- lib/Transforms/Utils/IntegerDivision.cpp	2014-11-05 13:28:24.000000000 -0800
-+++ lib/Transforms/Utils/IntegerDivision.cpp	2015-11-29 12:34:15.372349168 -0800
-@@ -401,7 +401,7 @@
-     // If we didn't actually generate an urem instruction, we're done
-     // This happens for example if the input were constant. In this case the
-     // Builder insertion point was unchanged
--    if (Rem == Builder.GetInsertPoint())
-+    if (Rem == Builder.GetInsertPoint().getNodePtrUnchecked())
-       return true;
- 
-     BinaryOperator *BO = dyn_cast<BinaryOperator>(Builder.GetInsertPoint());
-@@ -461,7 +461,7 @@
-     // If we didn't actually generate an udiv instruction, we're done
-     // This happens for example if the input were constant. In this case the
-     // Builder insertion point was unchanged
--    if (Div == Builder.GetInsertPoint())
-+    if (Div == Builder.GetInsertPoint().getNodePtrUnchecked())
-       return true;
- 
-     BinaryOperator *BO = dyn_cast<BinaryOperator>(Builder.GetInsertPoint());
---- lib/Transforms/Utils/LCSSA.cpp	2014-12-22 14:35:46.000000000 -0800
-+++ lib/Transforms/Utils/LCSSA.cpp	2015-11-29 12:35:57.149304063 -0800
-@@ -113,7 +113,8 @@
-       continue;
- 
-     PHINode *PN = PHINode::Create(Inst.getType(), PredCache.GetNumPreds(ExitBB),
--                                  Inst.getName() + ".lcssa", ExitBB->begin());
-+                                  Inst.getName() + ".lcssa",
-+                                  &ExitBB->front());
- 
-     // Add inputs from inside the loop for this PHI.
-     for (BasicBlock **PI = PredCache.GetPreds(ExitBB); *PI; ++PI) {
-@@ -161,8 +162,9 @@
-     if (isa<PHINode>(UserBB->begin()) && isExitBlock(UserBB, ExitBlocks)) {
-       // Tell the VHs that the uses changed. This updates SCEV's caches.
-       if (UsesToRewrite[i]->get()->hasValueHandle())
--        ValueHandleBase::ValueIsRAUWd(*UsesToRewrite[i], UserBB->begin());
--      UsesToRewrite[i]->set(UserBB->begin());
-+        ValueHandleBase::ValueIsRAUWd(*UsesToRewrite[i],
-+                                      &UserBB->front());
-+      UsesToRewrite[i]->set(&UserBB->front());
-       continue;
-     }
- 
---- lib/Transforms/Utils/Local.cpp	2015-02-08 19:35:35.000000000 -0800
-+++ lib/Transforms/Utils/Local.cpp	2015-11-29 12:57:42.322148975 -0800
-@@ -419,23 +419,24 @@
-   // or deleted by these simplifications. The idea of simplification is that it
-   // cannot introduce new instructions, and there is no way to replace the
-   // terminator of a block without introducing a new instruction.
--  AssertingVH<Instruction> TerminatorVH(--BB->end());
-+  AssertingVH<Instruction> TerminatorVH(&BB->back());
- #endif
- 
-   for (BasicBlock::iterator BI = BB->begin(), E = --BB->end(); BI != E; ) {
-     assert(!BI->isTerminator());
--    Instruction *Inst = BI++;
-+    Instruction *Inst = &*BI;
-+    ++BI;
- 
--    WeakVH BIHandle(BI);
-+    WeakVH BIHandle(&*BI);
-     if (recursivelySimplifyInstruction(Inst, TD, TLI)) {
-       MadeChange = true;
--      if (BIHandle != BI)
-+      if (BIHandle != &*BI)
-         BI = BB->begin();
-       continue;
-     }
- 
-     MadeChange |= RecursivelyDeleteTriviallyDeadInstructions(Inst, TLI);
--    if (BIHandle != BI)
-+    if (BIHandle != &*BI)
-       BI = BB->begin();
-   }
-   return MadeChange;
-@@ -804,7 +805,8 @@
- 
-     // Copy over any phi, debug or lifetime instruction.
-     BB->getTerminator()->eraseFromParent();
--    Succ->getInstList().splice(Succ->getFirstNonPHI(), BB->getInstList());
-+    Succ->getInstList().splice(Succ->getFirstNonPHI()->getIterator(),
-+                               BB->getInstList());
-   } else {
-     while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
-       // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
-@@ -1054,8 +1056,8 @@
-   DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
-   SmallVector<DbgDeclareInst *, 4> Dbgs;
-   for (auto &FI : F)
--    for (BasicBlock::iterator BI : FI)
--      if (auto DDI = dyn_cast<DbgDeclareInst>(BI))
-+    for (Instruction &BI : FI)
-+      if (auto DDI = dyn_cast<DbgDeclareInst>(&BI))
-         Dbgs.push_back(DDI);
- 
-   if (Dbgs.empty())
-@@ -1154,7 +1156,7 @@
-   new UnreachableInst(I->getContext(), I);
- 
-   // All instructions after this are dead.
--  BasicBlock::iterator BBI = I, BBE = BB->end();
-+  BasicBlock::iterator BBI = I->getIterator(), BBE = BB->end();
-   while (BBI != BBE) {
-     if (!BBI->use_empty())
-       BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
-@@ -1208,7 +1210,7 @@
- 
-           if (MakeUnreachable) {
-             // Don't insert a call to llvm.trap right before the unreachable.
--            changeToUnreachable(BBI, false);
-+            changeToUnreachable(&*BBI, false);
-             Changed = true;
-             break;
-           }
-@@ -1222,7 +1224,7 @@
-           ++BBI;
-           if (!isa<UnreachableInst>(BBI)) {
-             // Don't insert a call to llvm.trap right before the unreachable.
--            changeToUnreachable(BBI, false);
-+            changeToUnreachable(&*BBI, false);
-             Changed = true;
-           }
-           break;
-@@ -1279,7 +1281,7 @@
- /// otherwise.
- bool llvm::removeUnreachableBlocks(Function &F) {
-   SmallPtrSet<BasicBlock*, 128> Reachable;
--  bool Changed = markAliveBlocks(F.begin(), Reachable);
-+  bool Changed = markAliveBlocks(&F.front(), Reachable);
- 
-   // If there are unreachable blocks in the CFG...
-   if (Reachable.size() == F.size())
-@@ -1291,17 +1293,18 @@
-   // Loop over all of the basic blocks that are not reachable, dropping all of
-   // their internal references...
-   for (Function::iterator BB = ++F.begin(), E = F.end(); BB != E; ++BB) {
--    if (Reachable.count(BB))
-+    if (Reachable.count(&*BB))
-       continue;
- 
--    for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
-+    for (succ_iterator SI = succ_begin(&*BB), SE = succ_end(&*BB);
-+         SI != SE; ++SI)
-       if (Reachable.count(*SI))
--        (*SI)->removePredecessor(BB);
-+        (*SI)->removePredecessor(&*BB);
-     BB->dropAllReferences();
-   }
- 
-   for (Function::iterator I = ++F.begin(); I != F.end();)
--    if (!Reachable.count(I))
-+    if (!Reachable.count(&*I))
-       I = F.getBasicBlockList().erase(I);
-     else
-       ++I;
---- lib/Transforms/Utils/LoopSimplify.cpp	2015-01-04 04:03:27.000000000 -0800
-+++ lib/Transforms/Utils/LoopSimplify.cpp	2015-11-29 13:04:06.563171833 -0800
-@@ -76,7 +76,7 @@
-                                      SmallVectorImpl<BasicBlock *> &SplitPreds,
-                                      Loop *L) {
-   // Check to see if NewBB is already well placed.
--  Function::iterator BBI = NewBB; --BBI;
-+  Function::iterator BBI = --NewBB->getIterator();
-   for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
-     if (&*BBI == SplitPreds[i])
-       return;
-@@ -90,9 +90,8 @@
-   // block that neighbors a BB actually in the loop.
-   BasicBlock *FoundBB = nullptr;
-   for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
--    Function::iterator BBI = SplitPreds[i];
--    if (++BBI != NewBB->getParent()->end() &&
--        L->contains(BBI)) {
-+    Function::iterator BBI = SplitPreds[i]->getIterator();
-+    if (++BBI != NewBB->getParent()->end() && L->contains(&*BBI)) {
-       FoundBB = SplitPreds[i];
-       break;
-     }
-@@ -392,7 +391,7 @@
-                << BEBlock->getName() << "\n");
- 
-   // Move the new backedge block to right after the last backedge block.
--  Function::iterator InsertPos = BackedgeBlocks.back(); ++InsertPos;
-+  Function::iterator InsertPos = ++BackedgeBlocks.back()->getIterator();
-   F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock);
- 
-   // Now that the block has been inserted into the function, create PHI nodes in
-@@ -651,7 +650,7 @@
-       bool AllInvariant = true;
-       bool AnyInvariant = false;
-       for (BasicBlock::iterator I = ExitingBlock->begin(); &*I != BI; ) {
--        Instruction *Inst = I++;
-+        Instruction *Inst = &*I++;
-         // Skip debug info intrinsics.
-         if (isa<DbgInfoIntrinsic>(Inst))
-           continue;
---- lib/Transforms/Utils/LoopUnrollRuntime.cpp	2015-02-18 14:51:15.000000000 -0800
-+++ lib/Transforms/Utils/LoopUnrollRuntime.cpp	2015-11-29 13:08:21.195493550 -0800
-@@ -207,9 +207,9 @@
-   // Change the incoming values to the ones defined in the preheader or
-   // cloned loop.
-   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
--    PHINode *NewPHI = cast<PHINode>(VMap[I]);
-+    PHINode *NewPHI = cast<PHINode>(VMap[&*I]);
-     if (UnrollProlog) {
--      VMap[I] = NewPHI->getIncomingValueForBlock(Preheader);
-+      VMap[&*I] = NewPHI->getIncomingValueForBlock(Preheader);
-       cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI);
-     } else {
-       unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
-@@ -390,8 +390,8 @@
-                   VMap, LI);
- 
-   // Insert the cloned blocks into function just before the original loop
--  F->getBasicBlockList().splice(PEnd, F->getBasicBlockList(), NewBlocks[0],
--                                F->end());
-+  F->getBasicBlockList().splice(PEnd->getIterator(), F->getBasicBlockList(),
-+                                NewBlocks[0]->getIterator(), F->end());
- 
-   // Rewrite the cloned instruction operands to use the values
-   // created when the clone is created.
-@@ -399,7 +399,7 @@
-     for (BasicBlock::iterator I = NewBlocks[i]->begin(),
-                               E = NewBlocks[i]->end();
-          I != E; ++I) {
--      RemapInstruction(I, VMap,
-+      RemapInstruction(&*I, VMap,
-                        RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
-     }
-   }
---- lib/Transforms/Utils/LoopUnroll.cpp	2015-01-04 04:03:27.000000000 -0800
-+++ lib/Transforms/Utils/LoopUnroll.cpp	2015-11-29 13:06:17.558243110 -0800
-@@ -383,7 +383,7 @@
-     for (unsigned i = 0; i < NewBlocks.size(); ++i)
-       for (BasicBlock::iterator I = NewBlocks[i]->begin(),
-            E = NewBlocks[i]->end(); I != E; ++I)
--        ::RemapInstruction(I, LastValueMap);
-+        ::RemapInstruction(&*I, LastValueMap);
-   }
- 
-   // Loop over the PHI nodes in theinal block, setting incoming values.
-@@ -504,7 +504,7 @@
-   for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
-        BBE = NewLoopBlocks.end(); BB != BBE; ++BB)
-     for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {
--      Instruction *Inst = I++;
-+      Instruction *Inst = &*I++;
- 
-       if (isInstructionTriviallyDead(Inst))
-         (*BB)->getInstList().erase(Inst);
---- lib/Transforms/Utils/LowerExpectIntrinsic.cpp	2014-04-21 19:55:47.000000000 -0700
-+++ lib/Transforms/Utils/LowerExpectIntrinsic.cpp	2015-11-29 13:09:35.298686663 -0800
-@@ -148,7 +148,7 @@
- 
- bool LowerExpectIntrinsic::runOnFunction(Function &F) {
-   for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
--    BasicBlock *BB = I++;
-+    BasicBlock *BB = &*I++;
- 
-     // Create "block_weights" metadata.
-     if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
---- lib/Transforms/Utils/LowerInvoke.cpp	2014-04-21 19:55:47.000000000 -0700
-+++ lib/Transforms/Utils/LowerInvoke.cpp	2015-11-29 13:18:52.019842685 -0800
-@@ -69,7 +69,7 @@
-       BranchInst::Create(II->getNormalDest(), II);
- 
-       // Remove any PHI node entries from the exception destination.
--      II->getUnwindDest()->removePredecessor(BB);
-+      II->getUnwindDest()->removePredecessor(&*BB);
- 
-       // Remove the invoke instruction now.
-       BB->getInstList().erase(II);
---- lib/Transforms/Utils/LowerSwitch.cpp	2015-01-28 09:35:18.000000000 -0800
-+++ lib/Transforms/Utils/LowerSwitch.cpp	2015-11-29 13:39:46.489837410 -0800
-@@ -101,7 +101,8 @@
-   bool Changed = false;
- 
-   for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
--    BasicBlock *Cur = I++; // Advance over block so we don't traverse new blocks
-+    BasicBlock *Cur = &*I; // Advance over block so we don't traverse new blocks
-+    ++I;
- 
-     if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
-       Changed = true;
-@@ -142,7 +143,8 @@
- // number of phi values equal to the number of branches to SuccBB.
- static void fixPhis(BasicBlock *SuccBB, BasicBlock *OrigBB, BasicBlock *NewBB,
-                     unsigned NumMergedCases) {
--  for (BasicBlock::iterator I = SuccBB->begin(), IE = SuccBB->getFirstNonPHI();
-+  for (BasicBlock::iterator I = SuccBB->begin(),
-+       IE = SuccBB->getFirstNonPHI()->getIterator();
-        I != IE; ++I) {
-     PHINode *PN = cast<PHINode>(I);
- 
-@@ -256,8 +258,7 @@
-                                       UpperBound, Val, NewNode, OrigBlock,
-                                       Default);
- 
--  Function::iterator FI = OrigBlock;
--  F->getBasicBlockList().insert(++FI, NewNode);
-+  F->getBasicBlockList().insert(++OrigBlock->getIterator(), NewNode);
-   NewNode->getInstList().push_back(Comp);
- 
-   BranchInst::Create(LBranch, RBranch, Comp, NewNode);
-@@ -276,8 +277,7 @@
- {
-   Function* F = OrigBlock->getParent();
-   BasicBlock* NewLeaf = BasicBlock::Create(Val->getContext(), "LeafBlock");
--  Function::iterator FI = OrigBlock;
--  F->getBasicBlockList().insert(++FI, NewLeaf);
-+  F->getBasicBlockList().insert(++OrigBlock->getIterator(), NewLeaf);
- 
-   // Emit comparison
-   ICmpInst* Comp = nullptr;
-@@ -395,8 +395,7 @@
-   BasicBlock *NewDefault = nullptr;
-   if (!DefaultIsUnreachable) {
-     NewDefault = BasicBlock::Create(SI->getContext(), "NewDefault");
--    F->getBasicBlockList().insert(Default, NewDefault);
--
-+    F->getBasicBlockList().insert(Default->getIterator(), NewDefault);
-     BranchInst::Create(Default, NewDefault);
-   }
-   // If there is an entry in any PHI nodes for the default edge, make sure
---- lib/Transforms/Utils/PromoteMemoryToRegister.cpp	2015-01-04 04:03:27.000000000 -0800
-+++ lib/Transforms/Utils/PromoteMemoryToRegister.cpp	2015-11-29 13:44:30.613019495 -0800
-@@ -214,10 +214,11 @@
-     // avoid gratuitus rescans.
-     const BasicBlock *BB = I->getParent();
-     unsigned InstNo = 0;
--    for (BasicBlock::const_iterator BBI = BB->begin(), E = BB->end(); BBI != E;
--         ++BBI)
--      if (isInterestingInstruction(BBI))
--        InstNumbers[BBI] = InstNo++;
-+
-+    for (const Instruction &BBI : *BB)
-+      if (isInterestingInstruction(&BBI))
-+        InstNumbers[&BBI] = InstNo++;
-+
-     It = InstNumbers.find(I);
- 
-     assert(It != InstNumbers.end() && "Didn't insert instruction?");
-@@ -602,7 +603,7 @@
-     if (BBNumbers.empty()) {
-       unsigned ID = 0;
-       for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
--        BBNumbers[I] = ID++;
-+        BBNumbers[&*I] = ID++;
-     }
- 
-     // If we have an AST to keep updated, remember some pointer value that is
-@@ -641,7 +642,7 @@
-   // and inserting the phi nodes we marked as necessary
-   //
-   std::vector<RenamePassData> RenamePassWorkList;
--  RenamePassWorkList.push_back(RenamePassData(F.begin(), nullptr, Values));
-+  RenamePassWorkList.push_back(RenamePassData(&F.front(), nullptr, Values));
-   do {
-     RenamePassData RPD;
-     RPD.swap(RenamePassWorkList.back());
-@@ -946,7 +947,7 @@
-   // BasicBlock.
-   PN = PHINode::Create(Allocas[AllocaNo]->getAllocatedType(), getNumPreds(BB),
-                        Allocas[AllocaNo]->getName() + "." + Twine(Version++),
--                       BB->begin());
-+                       &BB->front());
-   ++NumPHIInsert;
-   PhiToAllocaMap[PN] = AllocaNo;
- 
-@@ -1011,7 +1012,8 @@
-     return;
- 
-   for (BasicBlock::iterator II = BB->begin(); !isa<TerminatorInst>(II);) {
--    Instruction *I = II++; // get the instruction, increment iterator
-+    Instruction *I = &*II; // get the instruction, increment iterator
-+    ++II;
- 
-     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
-       AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand());
---- lib/Transforms/Utils/SimplifyCFG.cpp	2015-01-12 20:17:47.000000000 -0800
-+++ lib/Transforms/Utils/SimplifyCFG.cpp	2015-11-29 15:07:34.912976680 -0800
-@@ -1091,15 +1091,15 @@
-   BasicBlock::iterator BB1_Itr = BB1->begin();
-   BasicBlock::iterator BB2_Itr = BB2->begin();
- 
--  Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
-+  Instruction *I1 = &*BB1_Itr++, *I2 = &*BB2_Itr++;
-   // Skip debug info if it is not identical.
-   DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
-   DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
-   if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
-     while (isa<DbgInfoIntrinsic>(I1))
--      I1 = BB1_Itr++;
-+      I1 = &*BB1_Itr++;
-     while (isa<DbgInfoIntrinsic>(I2))
--      I2 = BB2_Itr++;
-+      I2 = &*BB2_Itr++;
-   }
-   if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
-       (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
-@@ -1117,7 +1117,7 @@
-     // For a normal instruction, we just move one to right before the branch,
-     // then replace all uses of the other with the first.  Finally, we remove
-     // the now redundant second instruction.
--    BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
-+    BIParent->getInstList().splice(BI->getIterator(), BB1->getInstList(), I1);
-     if (!I2->use_empty())
-       I2->replaceAllUsesWith(I1);
-     I1->intersectOptionalDataWith(I2);
-@@ -1132,16 +1132,16 @@
-     I2->eraseFromParent();
-     Changed = true;
- 
--    I1 = BB1_Itr++;
--    I2 = BB2_Itr++;
-+    I1 = &*BB1_Itr++;
-+    I2 = &*BB2_Itr++;
-     // Skip debug info if it is not identical.
-     DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
-     DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
-     if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
-       while (isa<DbgInfoIntrinsic>(I1))
--        I1 = BB1_Itr++;
-+        I1 = &*BB1_Itr++;
-       while (isa<DbgInfoIntrinsic>(I2))
--        I2 = BB2_Itr++;
-+        I2 = &*BB2_Itr++;
-     }
-   } while (I1->isIdenticalToWhenDefined(I2));
- 
-@@ -1176,7 +1176,7 @@
- 
-   // Okay, it is safe to hoist the terminator.
-   Instruction *NT = I1->clone();
--  BIParent->getInstList().insert(BI, NT);
-+  BIParent->getInstList().insert(BI->getIterator(), NT);
-   if (!NT->getType()->isVoidTy()) {
-     I1->replaceAllUsesWith(NT);
-     I2->replaceAllUsesWith(NT);
-@@ -1353,7 +1353,7 @@
-       if (!NewPN) {
-         NewPN =
-             PHINode::Create(DifferentOp1->getType(), 2,
--                            DifferentOp1->getName() + ".sink", BBEnd->begin());
-+                            DifferentOp1->getName() + ".sink", &BBEnd->front());
-         NewPN->addIncoming(DifferentOp1, BB1);
-         NewPN->addIncoming(DifferentOp2, BB2);
-         DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";);
-@@ -1368,7 +1368,8 @@
-     // instruction in the basic block down.
-     bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->begin());
-     // Sink the instruction.
--    BBEnd->getInstList().splice(FirstNonPhiInBBEnd, BB1->getInstList(), I1);
-+    BBEnd->getInstList().splice(FirstNonPhiInBBEnd->getIterator(),
-+                                BB1->getInstList(), I1);
-     if (!OldPN->use_empty())
-       OldPN->replaceAllUsesWith(I1);
-     OldPN->eraseFromParent();
-@@ -1520,7 +1521,7 @@
-   for (BasicBlock::iterator BBI = ThenBB->begin(),
-                             BBE = std::prev(ThenBB->end());
-        BBI != BBE; ++BBI) {
--    Instruction *I = BBI;
-+    Instruction *I = &*BBI;
-     // Skip debug info.
-     if (isa<DbgInfoIntrinsic>(I))
-       continue;
-@@ -1632,8 +1633,8 @@
-   }
- 
-   // Hoist the instructions.
--  BB->getInstList().splice(BI, ThenBB->getInstList(), ThenBB->begin(),
--                           std::prev(ThenBB->end()));
-+  BB->getInstList().splice(BI->getIterator(), ThenBB->getInstList(),
-+                           ThenBB->begin(), std::prev(ThenBB->end()));
- 
-   // Insert selects and rewrite the PHI operands.
-   IRBuilder<true, NoFolder> Builder(BI);
-@@ -1776,13 +1777,13 @@
- 
-       // Check for trivial simplification.
-       if (Value *V = SimplifyInstruction(N, DL)) {
--        TranslateMap[BBI] = V;
-+        TranslateMap[&*BBI] = V;
-         delete N;   // Instruction folded away, don't need actual inst
-       } else {
-         // Insert the new instruction into its new home.
-         EdgeBB->getInstList().insert(InsertPt, N);
-         if (!BBI->use_empty())
--          TranslateMap[BBI] = N;
-+          TranslateMap[&*BBI] = N;
-       }
-     }
- 
-@@ -1875,8 +1876,9 @@
-     IfBlock1 = nullptr;
-   } else {
-     DomBlock = *pred_begin(IfBlock1);
--    for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
--      if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
-+    for (BasicBlock::iterator I = IfBlock1->begin();
-+         !isa<TerminatorInst>(I); ++I)
-+      if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
-         // This is not an aggressive instruction that we can promote.
-         // Because of this, we won't be able to get rid of the control
-         // flow, so the xform is not worth it.
-@@ -1888,8 +1890,9 @@
-     IfBlock2 = nullptr;
-   } else {
-     DomBlock = *pred_begin(IfBlock2);
--    for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
--      if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
-+    for (BasicBlock::iterator I = IfBlock2->begin();
-+         !isa<TerminatorInst>(I); ++I)
-+      if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
-         // This is not an aggressive instruction that we can promote.
-         // Because of this, we won't be able to get rid of the control
-         // flow, so the xform is not worth it.
-@@ -1908,13 +1911,13 @@
-   // Move all 'aggressive' instructions, which are defined in the
-   // conditional parts of the if's up to the dominating block.
-   if (IfBlock1)
--    DomBlock->getInstList().splice(InsertPt,
-+    DomBlock->getInstList().splice(InsertPt->getIterator(),
-                                    IfBlock1->getInstList(), IfBlock1->begin(),
--                                   IfBlock1->getTerminator());
-+                                   IfBlock1->getTerminator()->getIterator());
-   if (IfBlock2)
--    DomBlock->getInstList().splice(InsertPt,
-+    DomBlock->getInstList().splice(InsertPt->getIterator(),
-                                    IfBlock2->getInstList(), IfBlock2->begin(),
--                                   IfBlock2->getTerminator());
-+                                   IfBlock2->getTerminator()->getIterator());
- 
-   while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
-     // Change the PHI node into a select instruction.
-@@ -2086,7 +2089,8 @@
-              BI->getSuccessor(0) == PBI->getSuccessor(1))) {
-           for (BasicBlock::iterator I = BB->begin(), E = BB->end();
-                I != E; ) {
--            Instruction *Curr = I++;
-+            Instruction *Curr = &*I;
-+            ++I;
-             if (isa<CmpInst>(Curr)) {
-               Cond = Curr;
-               break;
-@@ -2106,7 +2110,7 @@
-   return false;
- 
-   // Make sure the instruction after the condition is the cond branch.
--  BasicBlock::iterator CondIt = Cond; ++CondIt;
-+  BasicBlock::iterator CondIt = ++Cond->getIterator();
- 
-   // Ignore dbg intrinsics.
-   while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
-@@ -2124,7 +2128,7 @@
-     // Ignore dbg intrinsics.
-     if (isa<DbgInfoIntrinsic>(I))
-       continue;
--    if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(I, DL))
-+    if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(&*I, DL))
-       return false;
-     // I has only one use and can be executed unconditionally.
-     Instruction *User = dyn_cast<Instruction>(I->user_back());
-@@ -2221,7 +2225,7 @@
-       Instruction *NewBonusInst = BonusInst->clone();
-       RemapInstruction(NewBonusInst, VMap,
-                        RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
--      VMap[BonusInst] = NewBonusInst;
-+      VMap[&*BonusInst] = NewBonusInst;
- 
-       // If we moved a load, we cannot any longer claim any knowledge about
-       // its potential value. The previous information might have been valid
-@@ -2230,8 +2234,8 @@
-       // semantics we don't understand.
-       NewBonusInst->dropUnknownMetadata(LLVMContext::MD_dbg);
- 
--      PredBlock->getInstList().insert(PBI, NewBonusInst);
--      NewBonusInst->takeName(BonusInst);
-+      PredBlock->getInstList().insert(PBI->getIterator(), NewBonusInst);
-+      NewBonusInst->takeName(&*BonusInst);
-       BonusInst->setName(BonusInst->getName() + ".old");
-     }
- 
-@@ -2240,7 +2244,7 @@
-     Instruction *New = Cond->clone();
-     RemapInstruction(New, VMap,
-                      RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
--    PredBlock->getInstList().insert(PBI, New);
-+    PredBlock->getInstList().insert(PBI->getIterator(), New);
-     New->takeName(Cond);
-     Cond->setName(New->getName() + ".old");
- 
-@@ -2392,7 +2396,7 @@
-       PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()),
-                                        std::distance(PB, PE),
-                                        BI->getCondition()->getName() + ".pr",
--                                       BB->begin());
-+                                       &BB->front());
-       // Okay, we're going to insert the PHI node.  Since PBI is not the only
-       // predecessor, compute the PHI'd conditional value for all of the preds.
-       // Any predecessor where the condition is not computable we keep symbolic.
-@@ -2877,7 +2881,9 @@
-   // then we evaluate them with an explicit branch first.  Split the block
-   // right before the condbr to handle it.
-   if (ExtraCase) {
--    BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test");
-+    BasicBlock *NewBB =
-+      BB->splitBasicBlock(BI->getIterator(), "switch.early.test");
-+
-     // Remove the uncond branch added to the old block.
-     TerminatorInst *OldTI = BB->getTerminator();
-     Builder.SetInsertPoint(OldTI);
-@@ -2943,7 +2949,7 @@
-     return false;
- 
-   // Check that there are no other instructions except for debug intrinsics.
--  BasicBlock::iterator I = LPInst, E = RI;
-+  BasicBlock::iterator I = LPInst->getIterator(), E = RI->getIterator();
-   while (++I != E)
-     if (!isa<DbgInfoIntrinsic>(I))
-       return false;
-@@ -3049,8 +3055,8 @@
- 
-   // If there are any instructions immediately before the unreachable that can
-   // be removed, do so.
--  while (UI != BB->begin()) {
--    BasicBlock::iterator BBI = UI;
-+  while (UI->getIterator() != BB->begin()) {
-+    BasicBlock::iterator BBI = UI->getIterator();
-     --BBI;
-     // Do not delete instructions that can have side effects which might cause
-     // the unreachable to not be reachable; specifically, calls and volatile
-@@ -3484,7 +3490,7 @@
-     } else if (isa<DbgInfoIntrinsic>(I)) {
-       // Skip debug intrinsic.
-       continue;
--    } else if (Constant *C = ConstantFold(I, ConstantPool, DL)) {
-+    } else if (Constant *C = ConstantFold(&*I, ConstantPool, DL)) {
-       // Instruction is side-effect free and constant.
- 
-       // If the instruction has uses outside this block or a phi node slot for
-@@ -3501,7 +3507,7 @@
-         return false;
-       }
- 
--      ConstantPool.insert(std::make_pair(I, C));
-+      ConstantPool.insert(std::make_pair(&*I, C));
-     } else {
-       break;
-     }
-@@ -4399,7 +4405,7 @@
-     return true;
- 
-   // If the Terminator is the only non-phi instruction, simplify the block.
--  BasicBlock::iterator I = BB->getFirstNonPHIOrDbg();
-+  BasicBlock::iterator I = BB->getFirstNonPHIOrDbg()->getIterator();
-   if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
-       TryToSimplifyUncondBranchFromEmptyBlock(BB))
-     return true;
---- lib/Transforms/Utils/SimplifyInstructions.cpp	2015-01-04 04:03:27.000000000 -0800
-+++ lib/Transforms/Utils/SimplifyInstructions.cpp	2015-11-29 15:09:24.682261310 -0800
-@@ -63,8 +63,11 @@
-         for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
-           // Here be subtlety: the iterator must be incremented before the loop
-           // body (not sure why), so a range-for loop won't work here.
--          for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
--            Instruction *I = BI++;
-+          for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
-+               BI != BE; /* inside loop */) {
-+            Instruction *I = &*BI;
-+            ++BI;
-+
-             // The first time through the loop ToSimplify is empty and we try to
-             // simplify all instructions.  On later iterations ToSimplify is not
-             // empty and we only bother simplifying instructions that are in it.
---- lib/Transforms/Utils/SimplifyLibCalls.cpp	2015-01-28 11:15:34.000000000 -0800
-+++ lib/Transforms/Utils/SimplifyLibCalls.cpp	2015-11-29 15:11:56.561911410 -0800
-@@ -1338,8 +1338,7 @@
-   if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
-     // If the argument is an instruction, it must dominate all uses so put our
-     // sincos call there.
--    BasicBlock::iterator Loc = ArgInst;
--    B.SetInsertPoint(ArgInst->getParent(), ++Loc);
-+    B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
-   } else {
-     // Otherwise (e.g. for a constant) the beginning of the function is as
-     // good a place as any.
---- lib/Transforms/Utils/UnifyFunctionExitNodes.cpp	2015-01-28 09:35:18.000000000 -0800
-+++ lib/Transforms/Utils/UnifyFunctionExitNodes.cpp	2015-11-29 15:14:01.147224983 -0800
-@@ -50,11 +50,12 @@
-   //
-   std::vector<BasicBlock*> ReturningBlocks;
-   std::vector<BasicBlock*> UnreachableBlocks;
--  for(Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
--    if (isa<ReturnInst>(I->getTerminator()))
--      ReturningBlocks.push_back(I);
--    else if (isa<UnreachableInst>(I->getTerminator()))
--      UnreachableBlocks.push_back(I);
-+
-+  for (BasicBlock &I : F)
-+    if (isa<ReturnInst>(I.getTerminator()))
-+      ReturningBlocks.push_back(&I);
-+    else if (isa<UnreachableInst>(I.getTerminator()))
-+      UnreachableBlocks.push_back(&I);
- 
-   // Then unreachable blocks.
-   if (UnreachableBlocks.empty()) {
---- lib/Transforms/Vectorize/BBVectorize.cpp	2014-12-19 09:21:38.000000000 -0800
-+++ lib/Transforms/Vectorize/BBVectorize.cpp	2015-12-06 09:35:21.191615227 -0800
-@@ -1243,12 +1243,13 @@
-       if (I == Start) IAfterStart = true;
- 
-       bool IsSimpleLoadStore;
--      if (!isInstVectorizable(I, IsSimpleLoadStore)) continue;
-+      if (!isInstVectorizable(&*I, IsSimpleLoadStore)) continue;
- 
-       // Look for an instruction with which to pair instruction *I...
-       DenseSet<Value *> Users;
-       AliasSetTracker WriteSet(*AA);
--      if (I->mayWriteToMemory()) WriteSet.add(I);
-+      if (I->mayWriteToMemory())
-+        WriteSet.add(&*I);
- 
-       bool JAfterStart = IAfterStart;
-       BasicBlock::iterator J = std::next(I);
-@@ -1256,7 +1257,7 @@
-         if (J == Start) JAfterStart = true;
- 
-         // Determine if J uses I, if so, exit the loop.
--        bool UsesI = trackUsesOfI(Users, WriteSet, I, J, !Config.FastDep);
-+        bool UsesI = trackUsesOfI(Users, WriteSet, &*I, &*J, !Config.FastDep);
-         if (Config.FastDep) {
-           // Note: For this heuristic to be effective, independent operations
-           // must tend to be intermixed. This is likely to be true from some
-@@ -1273,25 +1274,26 @@
-         // J does not use I, and comes before the first use of I, so it can be
-         // merged with I if the instructions are compatible.
-         int CostSavings, FixedOrder;
--        if (!areInstsCompatible(I, J, IsSimpleLoadStore, NonPow2Len,
--            CostSavings, FixedOrder)) continue;
-+        if (!areInstsCompatible(&*I, &*J, IsSimpleLoadStore, NonPow2Len,
-+                                CostSavings, FixedOrder))
-+          continue;
- 
-         // J is a candidate for merging with I.
-         if (!PairableInsts.size() ||
--             PairableInsts[PairableInsts.size()-1] != I) {
--          PairableInsts.push_back(I);
-+             PairableInsts[PairableInsts.size()-1] != &*I) {
-+          PairableInsts.push_back(&*I);
-         }
- 
--        CandidatePairs[I].push_back(J);
-+        CandidatePairs[&*I].push_back(&*J);
-         ++TotalPairs;
-         if (TTI)
--          CandidatePairCostSavings.insert(ValuePairWithCost(ValuePair(I, J),
--                                                            CostSavings));
-+          CandidatePairCostSavings.insert(
-+            ValuePairWithCost(ValuePair(&*I, &*J), CostSavings));
- 
-         if (FixedOrder == 1)
--          FixedOrderPairs.insert(ValuePair(I, J));
-+          FixedOrderPairs.insert(ValuePair(&*I, &*J));
-         else if (FixedOrder == -1)
--          FixedOrderPairs.insert(ValuePair(J, I));
-+          FixedOrderPairs.insert(ValuePair(&*J, &*I));
- 
-         // The next call to this function must start after the last instruction
-         // selected during this invocation.
-@@ -1472,14 +1474,15 @@
-     BasicBlock::iterator E = BB.end(), EL =
-       BasicBlock::iterator(cast<Instruction>(PairableInsts.back()));
-     for (BasicBlock::iterator I = BB.getFirstInsertionPt(); I != E; ++I) {
--      if (IsInPair.find(I) == IsInPair.end()) continue;
-+      if (IsInPair.find(&*I) == IsInPair.end())
-+        continue;
- 
-       DenseSet<Value *> Users;
-       AliasSetTracker WriteSet(*AA);
--      if (I->mayWriteToMemory()) WriteSet.add(I);
-+      if (I->mayWriteToMemory()) WriteSet.add(&*I);
- 
-       for (BasicBlock::iterator J = std::next(I); J != E; ++J) {
--        (void) trackUsesOfI(Users, WriteSet, I, J);
-+        (void) trackUsesOfI(Users, WriteSet, &*I, &*J);
- 
-         if (J == EL)
-           break;
-@@ -1488,7 +1491,7 @@
-       for (DenseSet<Value *>::iterator U = Users.begin(), E = Users.end();
-            U != E; ++U) {
-         if (IsInPair.find(*U) == IsInPair.end()) continue;
--        PairableInstUsers.insert(ValuePair(I, *U));
-+        PairableInstUsers.insert(ValuePair(&*I, *U));
-       }
- 
-       if (I == EL)
-@@ -2873,7 +2876,7 @@
-     if (I->mayWriteToMemory()) WriteSet.add(I);
- 
-     for (; cast<Instruction>(L) != J; ++L)
--      (void) trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSetPairs);
-+      (void) trackUsesOfI(Users, WriteSet, I, &*L, true, &LoadMoveSetPairs);
- 
-     assert(cast<Instruction>(L) == J &&
-       "Tracking has not proceeded far enough to check for dependencies");
-@@ -2895,9 +2898,10 @@
-     if (I->mayWriteToMemory()) WriteSet.add(I);
- 
-     for (; cast<Instruction>(L) != J;) {
--      if (trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSetPairs)) {
-+      if (trackUsesOfI(Users, WriteSet, I, &*L, true, &LoadMoveSetPairs)) {
-         // Move this instruction
--        Instruction *InstToMove = L; ++L;
-+        Instruction *InstToMove = &*L;
-+        ++L;
- 
-         DEBUG(dbgs() << "BBV: moving: " << *InstToMove <<
-                         " to after " << *InsertionPt << "\n");
-@@ -2929,10 +2933,10 @@
-     // farther down the use chain by another instruction pairing. Also, J
-     // could be before I if this is an inverted input.
-     for (BasicBlock::iterator E = BB.end(); cast<Instruction>(L) != E; ++L) {
--      if (trackUsesOfI(Users, WriteSet, I, L)) {
-+      if (trackUsesOfI(Users, WriteSet, I, &*L)) {
-         if (L->mayReadFromMemory()) {
--          LoadMoveSet[L].push_back(I);
--          LoadMoveSetPairs.insert(ValuePair(L, I));
-+          LoadMoveSet[&*L].push_back(I);
-+          LoadMoveSetPairs.insert(ValuePair(&*L, I));
-         }
-       }
-     }
-@@ -2995,7 +2999,7 @@
-     DEBUG(dbgs() << "BBV: initial: \n" << BB << "\n");
- 
-     for (BasicBlock::iterator PI = BB.getFirstInsertionPt(); PI != BB.end();) {
--      DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(PI);
-+      DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(&*PI);
-       if (P == ChosenPairs.end()) {
-         ++PI;
-         continue;
---- lib/Transforms/Vectorize/LoopVectorize.cpp	2015-02-17 13:53:25.000000000 -0800
-+++ lib/Transforms/Vectorize/LoopVectorize.cpp	2015-12-06 11:41:36.696287648 -0800
-@@ -462,6 +462,10 @@
-   Value *ExtendedIdx;
-   /// Maps scalars to widened vectors.
-   ValueMap WidenMap;
-+  /// Store instructions that should be predicated, as a pair
-+  ///    <StoreInst, Predicate>
-+  SmallVector<std::pair<StoreInst*,Value*>, 4> PredicatedStores;
-+
-   EdgeMaskCache MaskCache;
- 
-   LoopVectorizationLegality *Legal;
-@@ -1965,36 +1969,31 @@
-   // Create a new entry in the WidenMap and initialize it to Undef or Null.
-   VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
- 
--  Instruction *InsertPt = Builder.GetInsertPoint();
--  BasicBlock *IfBlock = Builder.GetInsertBlock();
--  BasicBlock *CondBlock = nullptr;
-+  // Instruction *InsertPt = Builder.GetInsertPoint();
-+  // BasicBlock *IfBlock = Builder.GetInsertBlock();
-+  // BasicBlock *CondBlock = nullptr;
- 
-   VectorParts Cond;
--  Loop *VectorLp = nullptr;
-+  //  Loop *VectorLp = nullptr;
-   if (IfPredicateStore) {
-     assert(Instr->getParent()->getSinglePredecessor() &&
-            "Only support single predecessor blocks");
-     Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
-                           Instr->getParent());
--    VectorLp = LI->getLoopFor(IfBlock);
--    assert(VectorLp && "Must have a loop for this block");
-+    // VectorLp = LI->getLoopFor(IfBlock);
-+    // assert(VectorLp && "Must have a loop for this block");
-   }
- 
-   // For each vector unroll 'part':
-   for (unsigned Part = 0; Part < UF; ++Part) {
-     // For each scalar that we create:
-     for (unsigned Width = 0; Width < VF; ++Width) {
--
-       // Start if-block.
-       Value *Cmp = nullptr;
-       if (IfPredicateStore) {
-         Cmp = Builder.CreateExtractElement(Cond[Part], Builder.getInt32(Width));
--        Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp, ConstantInt::get(Cmp->getType(), 1));
--        CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
--        LoopVectorBody.push_back(CondBlock);
--        VectorLp->addBasicBlockToLoop(CondBlock, LI->getBase());
--        // Update Builder with newly created basic block.
--        Builder.SetInsertPoint(InsertPt);
-+        Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp,
-+                                 ConstantInt::get(Cmp->getType(), 1));
-       }
- 
-       Instruction *Cloned = Instr->clone();
-@@ -2019,6 +2018,7 @@
-                                                        Builder.getInt32(Width));
-       // End if-block.
-       if (IfPredicateStore) {
-+#if 0
-          BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
-          LoopVectorBody.push_back(NewIfBlock);
-          VectorLp->addBasicBlockToLoop(NewIfBlock, LI->getBase());
-@@ -2027,6 +2027,9 @@
-          BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
-          OldBr->eraseFromParent();
-          IfBlock = NewIfBlock;
-+#endif
-+         PredicatedStores.push_back(std::make_pair(cast<StoreInst>(Cloned),
-+                                                   Cmp));
-       }
-     }
-   }
-@@ -2283,13 +2286,17 @@
- 
-   // Split the single block loop into the two loop structure described above.
-   BasicBlock *VectorPH =
--  BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
-+  BypassBlock->splitBasicBlock(BypassBlock->getTerminator()->getIterator(),
-+                               "vector.ph");
-   BasicBlock *VecBody =
--  VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
-+  VectorPH->splitBasicBlock(VectorPH->getTerminator()->getIterator(),
-+                            "vector.body");
-   BasicBlock *MiddleBlock =
--  VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
-+  VecBody->splitBasicBlock(VecBody->getTerminator()->getIterator(),
-+                           "middle.block");
-   BasicBlock *ScalarPH =
--  MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
-+  MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator()->getIterator(),
-+                               "scalar.ph");
- 
-   // Create and register the new vector loop.
-   Loop* Lp = new Loop();
-@@ -2378,7 +2385,8 @@
-   if (StrideCheck) {
-     // Create a new block containing the stride check.
-     BasicBlock *CheckBlock =
--        LastBypassBlock->splitBasicBlock(FirstCheckInst, "vector.stridecheck");
-+        LastBypassBlock->splitBasicBlock(FirstCheckInst->getIterator(),
-+                                         "vector.stridecheck");
-     if (ParentLoop)
-       ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
-     LoopBypassBlocks.push_back(CheckBlock);
-@@ -2402,7 +2410,8 @@
-   if (MemRuntimeCheck) {
-     // Create a new block containing the memory check.
-     BasicBlock *CheckBlock =
--        LastBypassBlock->splitBasicBlock(MemRuntimeCheck, "vector.memcheck");
-+        LastBypassBlock->splitBasicBlock(MemRuntimeCheck->getIterator(),
-+                                         "vector.memcheck");
-     if (ParentLoop)
-       ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
-     LoopBypassBlocks.push_back(CheckBlock);
-@@ -2590,7 +2599,7 @@
-   VecBody->getTerminator()->eraseFromParent();
- 
-   // Get ready to start creating new instructions into the vectorized body.
--  Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
-+  Builder.SetInsertPoint(&*VecBody->getFirstInsertionPt());
- 
-   // Save the state.
-   LoopVectorPreHeader = VectorPH;
-@@ -2739,7 +2748,8 @@
-   for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
-     BasicBlock *BB = BBs[i];
-     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
--      Instruction *In = I++;
-+      Instruction *In = &*I;
-+      ++I;
- 
-       if (!CSEDenseMapInfo::canHandle(In))
-         continue;
-@@ -2890,7 +2900,7 @@
-     // the PHIs and the values we are going to write.
-     // This allows us to write both PHINodes and the extractelement
-     // instructions.
--    Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
-+    Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
- 
-     VectorParts RdxParts;
-     setDebugLocFromInst(Builder, RdxDesc.LoopExitInstr);
-@@ -3000,6 +3010,9 @@
- 
-   fixLCSSAPHIs();
- 
-+  // Make sure DomTree is updated.
-+  updateAnalysis();
-+
-   // Remove redundant induction instructions.
-   cse(LoopVectorBody);
- }
-@@ -3084,8 +3097,9 @@
-       // This is phase one of vectorizing PHIs.
-       Type *VecTy = (VF == 1) ? PN->getType() :
-       VectorType::get(PN->getType(), VF);
--      Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
--                                    LoopVectorBody.back()-> getFirstInsertionPt());
-+      Entry[part] =
-+        PHINode::Create(VecTy, 2, "vec.phi",
-+                        &*LoopVectorBody.back()->getFirstInsertionPt());
-     }
-     PV->push_back(P);
-     return;
-@@ -3240,7 +3254,7 @@
- void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
-   // For each instruction in the old loop.
-   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
--    VectorParts &Entry = WidenMap.get(it);
-+    VectorParts &Entry = WidenMap.get(&*it);
-     switch (it->getOpcode()) {
-     case Instruction::Br:
-       // Nothing to do for PHIs and BR, since we already took care of the
-@@ -3248,7 +3262,7 @@
-       continue;
-     case Instruction::PHI:{
-       // Vectorize PHINodes.
--      widenPHIInstruction(it, Entry, UF, VF, PV);
-+      widenPHIInstruction(&*it, Entry, UF, VF, PV);
-       continue;
-     }// End of PHI.
- 
-@@ -3286,7 +3300,7 @@
-         Entry[Part] = V;
-       }
- 
--      propagateMetadata(Entry, it);
-+      propagateMetadata(Entry, &*it);
-       break;
-     }
-     case Instruction::Select: {
-@@ -3295,7 +3309,7 @@
-       // instruction with a scalar condition. Otherwise, use vector-select.
-       bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
-                                                OrigLoop);
--      setDebugLocFromInst(Builder, it);
-+      setDebugLocFromInst(Builder, &*it);
- 
-       // The condition can be loop invariant  but still defined inside the
-       // loop. This means that we can't just use theinal 'cond' value.
-@@ -3315,7 +3329,7 @@
-           Op1[Part]);
-       }
- 
--      propagateMetadata(Entry, it);
-+      propagateMetadata(Entry, &*it);
-       break;
-     }
- 
-@@ -3324,7 +3338,7 @@
-       // Widen compares. Generate vector compares.
-       bool FCmp = (it->getOpcode() == Instruction::FCmp);
-       CmpInst *Cmp = dyn_cast<CmpInst>(it);
--      setDebugLocFromInst(Builder, it);
-+      setDebugLocFromInst(Builder, &*it);
-       VectorParts &A = getVectorValue(it->getOperand(0));
-       VectorParts &B = getVectorValue(it->getOperand(1));
-       for (unsigned Part = 0; Part < UF; ++Part) {
-@@ -3336,13 +3350,13 @@
-         Entry[Part] = C;
-       }
- 
--      propagateMetadata(Entry, it);
-+      propagateMetadata(Entry, &*it);
-       break;
-     }
- 
-     case Instruction::Store:
-     case Instruction::Load:
--      vectorizeMemoryInstruction(it);
-+      vectorizeMemoryInstruction(&*it);
-         break;
-     case Instruction::ZExt:
-     case Instruction::SExt:
-@@ -3357,7 +3371,7 @@
-     case Instruction::FPTrunc:
-     case Instruction::BitCast: {
-       CastInst *CI = dyn_cast<CastInst>(it);
--      setDebugLocFromInst(Builder, it);
-+      setDebugLocFromInst(Builder, &*it);
-       /// Optimize the special case where the source is the induction
-       /// variable. Notice that we can only optimize the 'trunc' case
-       /// because: a. FP conversions lose precision, b. sext/zext may wrap,
-@@ -3369,7 +3383,7 @@
-         Value *Broadcasted = getBroadcastInstrs(ScalarCast);
-         for (unsigned Part = 0; Part < UF; ++Part)
-           Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
--        propagateMetadata(Entry, it);
-+        propagateMetadata(Entry, &*it);
-         break;
-       }
-       /// Vectorize casts.
-@@ -3379,7 +3393,7 @@
-       VectorParts &A = getVectorValue(it->getOperand(0));
-       for (unsigned Part = 0; Part < UF; ++Part)
-         Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
--      propagateMetadata(Entry, it);
-+      propagateMetadata(Entry, &*it);
-       break;
-     }
- 
-@@ -3387,7 +3401,7 @@
-       // Ignore dbg intrinsics.
-       if (isa<DbgInfoIntrinsic>(it))
-         break;
--      setDebugLocFromInst(Builder, it);
-+      setDebugLocFromInst(Builder, &*it);
- 
-       Module *M = BB->getParent()->getParent();
-       CallInst *CI = cast<CallInst>(it);
-@@ -3397,7 +3411,7 @@
-       case Intrinsic::assume:
-       case Intrinsic::lifetime_end:
-       case Intrinsic::lifetime_start:
--        scalarizeInstruction(it);
-+        scalarizeInstruction(&*it);
-         break;
-       default:
-         bool HasScalarOpd = hasVectorInstrinsicScalarOpd(ID, 1);
-@@ -3419,7 +3433,7 @@
-           Entry[Part] = Builder.CreateCall(F, Args);
-         }
- 
--        propagateMetadata(Entry, it);
-+        propagateMetadata(Entry, &*it);
-         break;
-       }
-       break;
-@@ -3427,7 +3441,7 @@
- 
-     default:
-       // All other instructions are unsupported. Scalarize them.
--      scalarizeInstruction(it);
-+      scalarizeInstruction(&*it);
-       break;
-     }// end of switch.
-   }// end of for_each instr.
-@@ -3686,7 +3700,7 @@
-         if (!PhiTy->isIntegerTy() &&
-             !PhiTy->isFloatingPointTy() &&
-             !PhiTy->isPointerTy()) {
--          emitAnalysis(Report(it)
-+          emitAnalysis(Report(&*it)
-                        << "loop control flow is not understood by vectorizer");
-           DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
-           return false;
-@@ -3698,16 +3712,17 @@
-         if (*bb != Header) {
-           // Check that this instruction has no outside users or is an
-           // identified reduction value with an outside user.
--          if (!hasOutsideLoopUser(TheLoop, it, AllowedExit))
-+          if (!hasOutsideLoopUser(TheLoop, &*it, AllowedExit))
-             continue;
--          emitAnalysis(Report(it) << "value could not be identified as "
--                                     "an induction or reduction variable");
-+          emitAnalysis(Report(&*it)
-+                       << "value could not be identified as "
-+                       "an induction or reduction variable");
-           return false;
-         }
- 
-         // We only allow if-converted PHIs with exactly two incoming values.
-         if (Phi->getNumIncomingValues() != 2) {
--          emitAnalysis(Report(it)
-+          emitAnalysis(Report(&*it)
-                        << "control flow not understood by vectorizer");
-           DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
-           return false;
-@@ -3739,9 +3754,10 @@
- 
-           // Until we explicitly handle the case of an induction variable with
-           // an outside loop user we have to give up vectorizing this loop.
--          if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
--            emitAnalysis(Report(it) << "use of induction value outside of the "
--                                       "loop is not handled by vectorizer");
-+          if (hasOutsideLoopUser(TheLoop, &*it, AllowedExit)) {
-+            emitAnalysis(Report(&*it) <<
-+                         "use of induction value outside of the "
-+                         "loop is not handled by vectorizer");
-             return false;
-           }
- 
-@@ -3786,8 +3802,8 @@
-           continue;
-         }
- 
--        emitAnalysis(Report(it) << "value that could not be identified as "
--                                   "reduction is used outside the loop");
-+        emitAnalysis(Report(&*it) << "value that could not be identified as "
-+                     "reduction is used outside the loop");
-         DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
-         return false;
-       }// end of PHI handling
-@@ -3796,7 +3812,7 @@
-       // calls and we do handle certain intrinsic and libm functions.
-       CallInst *CI = dyn_cast<CallInst>(it);
-       if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI)) {
--        emitAnalysis(Report(it) << "call instruction cannot be vectorized");
-+        emitAnalysis(Report(&*it) << "call instruction cannot be vectorized");
-         DEBUG(dbgs() << "LV: Found a call site.\n");
-         return false;
-       }
-@@ -3806,7 +3822,7 @@
-       if (CI &&
-           hasVectorInstrinsicScalarOpd(getIntrinsicIDForCall(CI, TLI), 1)) {
-         if (!SE->isLoopInvariant(SE->getSCEV(CI->getOperand(1)), TheLoop)) {
--          emitAnalysis(Report(it)
-+          emitAnalysis(Report(&*it)
-                        << "intrinsic instruction cannot be vectorized");
-           DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n");
-           return false;
-@@ -3817,7 +3833,7 @@
-       // Also, we can't vectorize extractelement instructions.
-       if ((!VectorType::isValidElementType(it->getType()) &&
-            !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) {
--        emitAnalysis(Report(it)
-+        emitAnalysis(Report(&*it)
-                      << "instruction return type cannot be vectorized");
-         DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
-         return false;
-@@ -3840,8 +3856,8 @@
- 
-       // Reduction instructions are allowed to have exit users.
-       // All other instructions must not have external users.
--      if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
--        emitAnalysis(Report(it) << "value cannot be used outside the loop");
-+      if (hasOutsideLoopUser(TheLoop, &*it, AllowedExit)) {
-+        emitAnalysis(Report(&*it) << "value cannot be used outside the loop");
-         return false;
-       }
- 
-@@ -4009,7 +4025,7 @@
-        BE = TheLoop->block_end(); B != BE; ++B)
-     for (BasicBlock::iterator I = (*B)->begin(), IE = (*B)->end();
-          I != IE; ++I)
--      if (I->getType()->isPointerTy() && isConsecutivePtr(I))
-+      if (I->getType()->isPointerTy() && isConsecutivePtr(&*I))
-         Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
- 
-   while (Worklist.size()) {
-@@ -4800,7 +4816,7 @@
-       if (it->mayWriteToMemory()) {
-         StoreInst *St = dyn_cast<StoreInst>(it);
-         if (!St) {
--          emitAnalysis(Report(it) << "instruction cannot be vectorized");
-+          emitAnalysis(Report(&*it) << "instruction cannot be vectorized");
-           return false;
-         }
-         if (!St->isSimple() && !IsAnnotatedParallel) {
-@@ -5543,7 +5559,7 @@
-       Type *T = it->getType();
- 
-       // Ignore ephemeral values.
--      if (EphValues.count(it))
-+      if (EphValues.count(&*it))
-         continue;
- 
-       // Only examine Loads, Stores and PHINodes.
-@@ -5562,7 +5578,7 @@
-       // Ignore loaded pointer types and stored pointer types that are not
-       // consecutive. However, we do want to take consecutive stores/loads of
-       // pointer vectors into account.
--      if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
-+      if (T->isPointerTy() && !isConsecutiveLoadOrStore(&*it))
-         continue;
- 
-       MaxWidth = std::max(MaxWidth,
-@@ -5765,7 +5781,7 @@
-     R.NumInstructions += (*bb)->size();
-     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
-          ++it) {
--      Instruction *I = it;
-+      Instruction *I = &*it;
-       IdxToInstr[Index++] = I;
- 
-       // Save the end location of each USE.
-@@ -5853,10 +5869,10 @@
-         continue;
- 
-       // Ignore ephemeral values.
--      if (EphValues.count(it))
-+      if (EphValues.count(&*it))
-         continue;
- 
--      unsigned C = getInstructionCost(it, VF);
-+      unsigned C = getInstructionCost(&*it, VF);
- 
-       // Check if we should override the cost.
-       if (ForceTargetInstructionCost.getNumOccurrences() > 0)
-@@ -6230,19 +6246,12 @@
-   // Create a new entry in the WidenMap and initialize it to Undef or Null.
-   VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
- 
--  Instruction *InsertPt = Builder.GetInsertPoint();
--  BasicBlock *IfBlock = Builder.GetInsertBlock();
--  BasicBlock *CondBlock = nullptr;
--
-   VectorParts Cond;
--  Loop *VectorLp = nullptr;
-   if (IfPredicateStore) {
-     assert(Instr->getParent()->getSinglePredecessor() &&
-            "Only support single predecessor blocks");
-     Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
-                           Instr->getParent());
--    VectorLp = LI->getLoopFor(IfBlock);
--    assert(VectorLp && "Must have a loop for this block");
-   }
- 
-   // For each vector unroll 'part':
-@@ -6257,11 +6266,6 @@
-             Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0));
-       Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part],
-                                ConstantInt::get(Cond[Part]->getType(), 1));
--      CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
--      LoopVectorBody.push_back(CondBlock);
--      VectorLp->addBasicBlockToLoop(CondBlock, LI->getBase());
--      // Update Builder with newly created basic block.
--      Builder.SetInsertPoint(InsertPt);
-     }
- 
-     Instruction *Cloned = Instr->clone();
-@@ -6282,16 +6286,9 @@
-         VecResults[Part] = Cloned;
- 
-     // End if-block.
--      if (IfPredicateStore) {
--        BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
--        LoopVectorBody.push_back(NewIfBlock);
--        VectorLp->addBasicBlockToLoop(NewIfBlock, LI->getBase());
--        Builder.SetInsertPoint(InsertPt);
--        Instruction *OldBr = IfBlock->getTerminator();
--        BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
--        OldBr->eraseFromParent();
--        IfBlock = NewIfBlock;
--      }
-+      if (IfPredicateStore)
-+        PredicatedStores.push_back(std::make_pair(cast<StoreInst>(Cloned),
-+                                                  Cmp));
-   }
- }
- 
---- lib/Transforms/Vectorize/SLPVectorizer.cpp	2015-02-12 09:51:17.000000000 -0800
-+++ lib/Transforms/Vectorize/SLPVectorizer.cpp	2015-12-06 11:52:23.656576722 -0800
-@@ -1742,7 +1742,8 @@
-     }    
- 
-     // Now find the sequence of instructions between PrevInst and Inst.
--    BasicBlock::reverse_iterator InstIt(Inst), PrevInstIt(PrevInst);
-+    BasicBlock::reverse_iterator InstIt(Inst->getIterator()),
-+      PrevInstIt(PrevInst->getIterator());
-     --PrevInstIt;
-     while (InstIt != PrevInstIt) {
-       if (PrevInstIt == PrevInst->getParent()->rend()) {
-@@ -1890,7 +1891,7 @@
- 
- void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
-   Instruction *VL0 = cast<Instruction>(VL[0]);
--  BasicBlock::iterator NextInst = VL0;
-+  BasicBlock::iterator NextInst(VL0);
-   ++NextInst;
-   Builder.SetInsertPoint(VL0->getParent(), NextInst);
-   Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
-@@ -2346,7 +2347,7 @@
-     scheduleBlock(BSIter.second.get());
-   }
- 
--  Builder.SetInsertPoint(F->getEntryBlock().begin());
-+  Builder.SetInsertPoint(&F->getEntryBlock().front());
-   vectorizeTree(&VectorizableTree[0]);
- 
-   DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
-@@ -2391,7 +2392,7 @@
-         User->replaceUsesOfWith(Scalar, Ex);
-      }
-     } else {
--      Builder.SetInsertPoint(F->getEntryBlock().begin());
-+      Builder.SetInsertPoint(&F->getEntryBlock().front());
-       Value *Ex = Builder.CreateExtractElement(Vec, Lane);
-       CSEBlocks.insert(&F->getEntryBlock());
-       User->replaceUsesOfWith(Scalar, Ex);
-@@ -2500,7 +2501,9 @@
-     BasicBlock *BB = (*I)->getBlock();
-     // For all instructions in blocks containing gather sequences:
-     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
--      Instruction *In = it++;
-+      Instruction *In = &*it;
-+      ++it;
-+
-       if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
-         continue;
- 
-@@ -2648,7 +2651,7 @@
-   }
-   // Search up and down at the same time, because we don't know if the new
-   // instruction is above or below the existing scheduling region.
--  BasicBlock::reverse_iterator UpIter(ScheduleStart);
-+  BasicBlock::reverse_iterator UpIter(ScheduleStart->getIterator());
-   BasicBlock::reverse_iterator UpperEnd = BB->rend();
-   BasicBlock::iterator DownIter(ScheduleEnd);
-   BasicBlock::iterator LowerEnd = BB->end();
-@@ -2860,7 +2863,8 @@
-       Instruction *pickedInst = BundleMember->Inst;
-       if (LastScheduledInst->getNextNode() != pickedInst) {
-         BS->BB->getInstList().remove(pickedInst);
--        BS->BB->getInstList().insert(LastScheduledInst, pickedInst);
-+        BS->BB->getInstList().insert(LastScheduledInst->getIterator(),
-+                                     pickedInst);
-       }
-       LastScheduledInst = pickedInst;
-       BundleMember = BundleMember->NextInBundle;
-@@ -3243,8 +3247,8 @@
-         Instruction *InsertAfter = cast<Instruction>(BuildVectorSlice.back());
-         unsigned VecIdx = 0;
-         for (auto &V : BuildVectorSlice) {
--          IRBuilder<true, NoFolder> Builder(
--              ++BasicBlock::iterator(InsertAfter));
-+          IRBuilder<true, NoFolder> Builder(InsertAfter->getParent(),
-+                                   ++BasicBlock::iterator(InsertAfter));
-           InsertElementInst *IE = cast<InsertElementInst>(V);
-           Instruction *Extract = cast<Instruction>(Builder.CreateExtractElement(
-               VectorizedRoot, Builder.getInt32(VecIdx++)));
-@@ -3695,10 +3699,10 @@
- 
-   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
-     // We may go through BB multiple times so skip the one we have checked.
--    if (!VisitedInstrs.insert(it).second)
-+    if (!VisitedInstrs.insert(&*it).second)
-       continue;
- 
--    if (isa<DbgInfoIntrinsic>(it))
-+    if (isa<DbgInfoIntrinsic>(&*it))
-       continue;
- 
-     // Try to vectorize reductions that use PHINodes.
---- tools/bugpoint/CrashDebugger.cpp	2014-08-26 10:19:03.000000000 -0700
-+++ tools/bugpoint/CrashDebugger.cpp	2015-12-08 17:47:24.061167860 -0800
-@@ -148,7 +148,7 @@
-   // playing with...
-   for (Module::global_iterator I = M->global_begin(), E = M->global_end();
-        I != E; ++I)
--    if (I->hasInitializer() && !GVSet.count(I)) {
-+    if (I->hasInitializer() && !GVSet.count(&*I)) {
-       I->setInitializer(nullptr);
-       I->setLinkage(GlobalValue::ExternalLinkage);
-     }
-@@ -222,8 +222,8 @@
-   // Loop over and delete any functions which we aren't supposed to be playing
-   // with...
-   for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
--    if (!I->isDeclaration() && !Functions.count(I))
--      DeleteFunctionBody(I);
-+    if (!I->isDeclaration() && !Functions.count(&*I))
-+      DeleteFunctionBody(&*I);
- 
-   // Try running the hacked up program...
-   if (TestFn(BD, M)) {
-@@ -289,11 +289,12 @@
-   // Loop over and delete any hack up any blocks that are not listed...
-   for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
-     for (Function::iterator BB = I->begin(), E = I->end(); BB != E; ++BB)
--      if (!Blocks.count(BB) && BB->getTerminator()->getNumSuccessors()) {
-+      if (!Blocks.count(&*BB) && BB->getTerminator()->getNumSuccessors()) {
-         // Loop over all of the successors of this block, deleting any PHI nodes
-         // that might include it.
--        for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
--          (*SI)->removePredecessor(BB);
-+        for (succ_iterator SI = succ_begin(&*BB), E = succ_end(&*BB);
-+             SI != E; ++SI)
-+          (*SI)->removePredecessor(&*BB);
- 
-         TerminatorInst *BBTerm = BB->getTerminator();
-         
-@@ -302,7 +303,7 @@
- 
-         // Replace the old terminator instruction.
-         BB->getInstList().pop_back();
--        new UnreachableInst(BB->getContext(), BB);
-+        new UnreachableInst(BB->getContext(), &*BB);
-       }
- 
-   // The CFG Simplifier pass may delete one of the basic blocks we are
-@@ -397,7 +398,8 @@
-   for (Module::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI)
-     for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE; ++FI)
-       for (BasicBlock::iterator I = FI->begin(), E = FI->end(); I != E;) {
--        Instruction *Inst = I++;
-+        Instruction *Inst = &*I;
-+        ++I;
-         if (!Instructions.count(Inst) && !isa<TerminatorInst>(Inst) &&
-             !isa<LandingPadInst>(Inst)) {
-           if (!Inst->getType()->isVoidTy())
-@@ -468,7 +470,7 @@
-         for (Module::global_iterator I = BD.getProgram()->global_begin(),
-                E = BD.getProgram()->global_end(); I != E; ++I)
-           if (I->hasInitializer())
--            GVs.push_back(I);
-+            GVs.push_back(&*I);
- 
-         if (GVs.size() > 1 && !BugpointIsInterrupted) {
-           outs() << "\n*** Attempting to reduce the number of global "
-@@ -491,7 +493,7 @@
-   for (Module::iterator I = BD.getProgram()->begin(),
-          E = BD.getProgram()->end(); I != E; ++I)
-     if (!I->isDeclaration())
--      Functions.push_back(I);
-+      Functions.push_back(&*I);
- 
-   if (Functions.size() > 1 && !BugpointIsInterrupted) {
-     outs() << "\n*** Attempting to reduce the number of functions "
-@@ -511,10 +513,11 @@
-   //
-   if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
-     std::vector<const BasicBlock*> Blocks;
--    for (Module::const_iterator I = BD.getProgram()->begin(),
--           E = BD.getProgram()->end(); I != E; ++I)
--      for (Function::const_iterator FI = I->begin(), E = I->end(); FI !=E; ++FI)
--        Blocks.push_back(FI);
-+    for (Function &F : *BD.getProgram()) {
-+      for (BasicBlock &BB : F)
-+        Blocks.push_back(&BB);
-+    }
-+
-     unsigned OldSize = Blocks.size();
-     ReduceCrashingBlocks(BD, TestFn).reduceList(Blocks, Error);
-     if (Blocks.size() < OldSize)
-@@ -525,14 +528,11 @@
-   // cases with large basic blocks where the problem is at one end.
-   if (!BugpointIsInterrupted) {
-     std::vector<const Instruction*> Insts;
--    for (Module::const_iterator MI = BD.getProgram()->begin(),
--           ME = BD.getProgram()->end(); MI != ME; ++MI)
--      for (Function::const_iterator FI = MI->begin(), FE = MI->end(); FI != FE;
--           ++FI)
--        for (BasicBlock::const_iterator I = FI->begin(), E = FI->end();
--             I != E; ++I)
--          if (!isa<TerminatorInst>(I))
--            Insts.push_back(I);
-+    for (const Function &F : *BD.getProgram())
-+      for (const BasicBlock &BB : F)
-+        for (const Instruction &I : BB)
-+          if (!isa<TerminatorInst>(&I))
-+            Insts.push_back(&I);
- 
-     ReduceCrashingInstructions(BD, TestFn).reduceList(Insts, Error);
-   }
-@@ -577,7 +577,7 @@
- 
-               outs() << "Checking instruction: " << *I;
-               std::unique_ptr<Module> M =
--                  BD.deleteInstructionFromProgram(I, Simplification);
-+                  BD.deleteInstructionFromProgram(&*I, Simplification);
- 
-               // Find out if the pass still crashes on this pass...
-               if (TestFn(BD, M.get())) {
---- tools/bugpoint/ExtractFunction.cpp	2014-08-26 10:19:03.000000000 -0700
-+++ tools/bugpoint/ExtractFunction.cpp	2015-12-08 17:53:34.720329668 -0800
-@@ -100,7 +100,7 @@
- 
-   BasicBlock::iterator RI = RBI->begin(); // Get iterator to corresponding inst
-   std::advance(RI, std::distance(PBB->begin(), BasicBlock::const_iterator(I)));
--  Instruction *TheInst = RI;              // Got the corresponding instruction!
-+  Instruction *TheInst = &*RI;           // Got the corresponding instruction!
- 
-   // If this instruction produces a value, replace any users with null values
-   if (!TheInst->getType()->isVoidTy())
-@@ -307,15 +307,15 @@
-   
-   // Remove the Safe functions from the Test module
-   for (Module::iterator I = New->begin(), E = New->end(); I != E; ++I)
--    if (!TestFunctions.count(I))
--      DeleteFunctionBody(I);
-+    if (!TestFunctions.count(&*I))
-+      DeleteFunctionBody(&*I);
-   
- 
-   // Try to split the global initializers evenly
-   for (Module::global_iterator I = M->global_begin(), E = M->global_end();
-        I != E; ++I) {
--    GlobalVariable *GV = cast<GlobalVariable>(NewVMap[I]);
--    if (Function *TestFn = globalInitUsesExternalBA(I)) {
-+    GlobalVariable *GV = cast<GlobalVariable>(NewVMap[&*I]);
-+    if (Function *TestFn = globalInitUsesExternalBA(&*I)) {
-       if (Function *SafeFn = globalInitUsesExternalBA(GV)) {
-         errs() << "*** Error: when reducing functions, encountered "
-                   "the global '";
---- tools/bugpoint/Miscompilation.cpp	2014-10-27 17:24:16.000000000 -0700
-+++ tools/bugpoint/Miscompilation.cpp	2015-12-08 17:55:31.425007898 -0800
-@@ -550,7 +550,7 @@
-   for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
-     for (Function::iterator I = MiscompiledFunctions[i]->begin(),
-            E = MiscompiledFunctions[i]->end(); I != E; ++I)
--      Blocks.push_back(I);
-+      Blocks.push_back(&*I);
- 
-   // Use the list reducer to identify blocks that can be extracted without
-   // obscuring the bug.  The Blocks list will end up containing blocks that must
-@@ -634,7 +634,7 @@
-   Module *Prog = BD.getProgram();
-   for (Module::iterator I = Prog->begin(), E = Prog->end(); I != E; ++I)
-     if (!I->isDeclaration())
--      MiscompiledFunctions.push_back(I);
-+      MiscompiledFunctions.push_back(&*I);
- 
-   // Do the reduction...
-   if (!BugpointIsInterrupted)
-@@ -806,7 +806,7 @@
-              I = newMain->arg_begin(), E = newMain->arg_end(),
-              OI = oldMain->arg_begin(); I != E; ++I, ++OI) {
-         I->setName(OI->getName());    // Copy argument names from oldMain
--        args.push_back(I);
-+        args.push_back(&*I);
-       }
- 
-       // Call the old main function and return its result
-@@ -910,7 +910,7 @@
-           std::vector<Value*> Args;
-           for (Function::arg_iterator i = FuncWrapper->arg_begin(),
-                  e = FuncWrapper->arg_end(); i != e; ++i)
--            Args.push_back(i);
-+            Args.push_back(&*i);
- 
-           // Pass on the arguments to the real function, return its result
-           if (F->getReturnType()->isVoidTy()) {
---- tools/clang/include/clang/Analysis/CFG.h	2015-10-05 11:01:32.409005315 -0700
-+++ tools/clang/include/clang/Analysis/CFG.h	2015-12-08 08:12:46.482439723 -0800
-@@ -322,7 +322,7 @@
-   Stmt &operator*() { return *getStmt(); }
-   const Stmt &operator*() const { return *getStmt(); }
- 
--  LLVM_EXPLICIT operator bool() const { return getStmt(); }
-+  explicit operator bool() const { return getStmt(); }
- };
- 
- /// CFGBlock - Represents a single basic block in a source-level CFG.
-@@ -432,7 +432,7 @@
-   public:
-     /// Construct an AdjacentBlock with a possibly unreachable block.
-     AdjacentBlock(CFGBlock *B, bool IsReachable);
--    
-+
-     /// Construct an AdjacentBlock with a reachable block and an alternate
-     /// unreachable block.
-     AdjacentBlock(CFGBlock *B, CFGBlock *AlternateBlock);
-@@ -694,7 +694,7 @@
-   iterator beginAutomaticObjDtorsInsert(iterator I, size_t Cnt,
-       BumpVectorContext &C) {
-     return iterator(Elements.insert(I.base(), Cnt,
--                                    CFGAutomaticObjDtor(nullptr, 0), C));
-+                                    CFGAutomaticObjDtor(nullptr, nullptr), C));
-   }
-   iterator insertAutomaticObjDtor(iterator I, VarDecl *VD, Stmt *S) {
-     *I = CFGAutomaticObjDtor(VD, S);
-@@ -767,7 +767,7 @@
-   /// (not a pointer to CFGBlock).
-   class graph_iterator {
-   public:
--    typedef const CFGBlock                  value_type;
-+    typedef CFGBlock                        value_type;
-     typedef value_type&                     reference;
-     typedef value_type*                     pointer;
-     typedef BumpVector<CFGBlock*>::iterator ImplTy;
---- tools/clang/lib/Frontend/Rewrite/InclusionRewriter.cpp	2015-10-05 11:01:32.364932580 -0700
-+++ tools/clang/lib/Frontend/Rewrite/InclusionRewriter.cpp	2015-10-12 22:15:59.378584335 -0700
-@@ -285,16 +285,11 @@
-   do {
-     DirectiveLex.LexFromRawLexer(DirectiveToken);
-   } while (!DirectiveToken.is(tok::eod) && DirectiveToken.isNot(tok::eof));
-+
-   if (&FromFile == PredefinesBuffer) {
-     // OutputContentUpTo() would not output anything anyway.
-     return;
-   }
--  OS << "#if 0 /* expanded by -frewrite-includes */" << MainEOL;
--  OutputContentUpTo(FromFile, NextToWrite,
--                    SM.getFileOffset(DirectiveToken.getLocation()) +
--                        DirectiveToken.getLength(),
--                    LocalEOL, Line, true);
--  OS << "#endif /* expanded by -frewrite-includes */" << MainEOL;
- }
- 
- /// Find the next identifier in the pragma directive specified by \p RawToken.
---- tools/clang/lib/StaticAnalyzer/Core/BugReporter.cpp	2015-10-05 11:01:32.334095518 -0700
-+++ tools/clang/lib/StaticAnalyzer/Core/BugReporter.cpp	2015-12-08 09:02:55.503942822 -0800
-@@ -3295,11 +3295,11 @@
-   // post-dominated by a sink, simply add all the nodes in the equivalence class
-   // to 'Nodes'.  Any of the reports will serve as a "representative" report.
-   if (!BT.isSuppressOnSink()) {
--    BugReport *R = I;
-+    BugReport *R = &*I;
-     for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I) {
-       const ExplodedNode *N = I->getErrorNode();
-       if (N) {
--        R = I;
-+        R = &*I;
-         bugReports.push_back(R);
-       }
-     }
-@@ -3325,35 +3325,35 @@
-     }
-     // No successors?  By definition this nodes isn't post-dominated by a sink.
-     if (errorNode->succ_empty()) {
--      bugReports.push_back(I);
-+      bugReports.push_back(&*I);
-       if (!exampleReport)
--        exampleReport = I;
-+        exampleReport = &*I;
-       continue;
-     }
- 
-     // At this point we know that 'N' is not a sink and it has at least one
--    // successor.  Use a DFS worklist to find a non-sink end-of-path node.    
-+    // successor.  Use a DFS worklist to find a non-sink end-of-path node.
-     typedef FRIEC_WLItem WLItem;
-     typedef SmallVector<WLItem, 10> DFSWorkList;
-     llvm::DenseMap<const ExplodedNode *, unsigned> Visited;
--    
-+
-     DFSWorkList WL;
-     WL.push_back(errorNode);
-     Visited[errorNode] = 1;
--    
-+
-     while (!WL.empty()) {
-       WLItem &WI = WL.back();
-       assert(!WI.N->succ_empty());
--            
-+
-       for (; WI.I != WI.E; ++WI.I) {
--        const ExplodedNode *Succ = *WI.I;        
-+        const ExplodedNode *Succ = *WI.I;
-         // End-of-path node?
-         if (Succ->succ_empty()) {
-           // If we found an end-of-path node that is not a sink.
-           if (!Succ->isSink()) {
--            bugReports.push_back(I);
-+            bugReports.push_back(&*I);
-             if (!exampleReport)
--              exampleReport = I;
-+              exampleReport = &*I;
-             WL.clear();
-             break;
-           }
---- tools/llvm-diff/DifferenceEngine.cpp	2014-07-21 10:06:51.000000000 -0700
-+++ tools/llvm-diff/DifferenceEngine.cpp	2015-12-08 13:51:00.260552197 -0800
-@@ -599,7 +599,7 @@
-   TerminatorInst *RTerm = RStart->getParent()->getTerminator();
-   if (isa<BranchInst>(LTerm) && isa<InvokeInst>(RTerm)) {
-     if (cast<BranchInst>(LTerm)->isConditional()) return;
--    BasicBlock::iterator I = LTerm;
-+    BasicBlock::iterator I = LTerm->getIterator();
-     if (I == LStart->getParent()->begin()) return;
-     --I;
-     if (!isa<CallInst>(*I)) return;
-@@ -612,7 +612,7 @@
-     tryUnify(LTerm->getSuccessor(0), RInvoke->getNormalDest());
-   } else if (isa<InvokeInst>(LTerm) && isa<BranchInst>(RTerm)) {
-     if (cast<BranchInst>(RTerm)->isConditional()) return;
--    BasicBlock::iterator I = RTerm;
-+    BasicBlock::iterator I = RTerm->getIterator();
-     if (I == RStart->getParent()->begin()) return;
-     --I;
-     if (!isa<CallInst>(*I)) return;
---- tools/llvm-stress/llvm-stress.cpp	2014-08-25 11:16:47.000000000 -0700
-+++ tools/llvm-stress/llvm-stress.cpp	2015-12-08 17:59:08.743284003 -0800
-@@ -622,7 +622,7 @@
-   // Consider arguments as legal values.
-   for (Function::arg_iterator it = F->arg_begin(), e = F->arg_end();
-        it != e; ++it)
--    PT.push_back(it);
-+    PT.push_back(&*it);
- 
-   // List of modifiers which add new random instructions.
-   std::vector<Modifier*> Modifiers;
-@@ -663,16 +663,15 @@
-   for (BasicBlock::iterator it = F->begin()->begin(),
-        e = F->begin()->end(); it != e; ++it) {
-     if (it->getType() == IntegerType::getInt1Ty(F->getContext()))
--      BoolInst.push_back(it);
-+      BoolInst.push_back(&*it);
-   }
- 
-   std::random_shuffle(BoolInst.begin(), BoolInst.end(), R);
- 
--  for (std::vector<Instruction*>::iterator it = BoolInst.begin(),
--       e = BoolInst.end(); it != e; ++it) {
--    Instruction *Instr = *it;
-+
-+  for (auto *Instr : BoolInst) {
-     BasicBlock *Curr = Instr->getParent();
--    BasicBlock::iterator Loc= Instr;
-+    BasicBlock::iterator Loc = Instr->getIterator();
-     BasicBlock *Next = Curr->splitBasicBlock(Loc, "CF");
-     Instr->moveBefore(Curr->getTerminator());
-     if (Curr != &F->getEntryBlock()) {
---- unittests/ADT/ilistTest.cpp	2014-06-08 15:29:17.000000000 -0700
-+++ unittests/ADT/ilistTest.cpp	2016-01-23 11:05:55.000000000 -0800
-@@ -80,7 +80,7 @@
-   // List with contents.
-   List.push_back(1);
-   ASSERT_EQ(1u, List.size());
--  Node *N = List.begin();
-+  Node *N = &*List.begin();
-   EXPECT_EQ(1, N->Value);
-   List.clearAndLeakNodesUnsafely();
-   EXPECT_EQ(0u, List.size());
---- unittests/Analysis/CFGTest.cpp	2014-08-19 09:58:54.000000000 -0700
-+++ unittests/Analysis/CFGTest.cpp	2016-01-23 11:08:10.000000000 -0800
-@@ -378,7 +378,7 @@
- TEST_F(IsPotentiallyReachableTest, ModifyTest) {
-   ParseAssembly(BranchInsideLoopIR);
- 
--  succ_iterator S = succ_begin(++M->getFunction("test")->begin());
-+  succ_iterator S = succ_begin(&*++M->getFunction("test")->begin());
-   BasicBlock *OldBB = S[0];
-   S[0] = S[1];
-   ExpectPath(false);
---- unittests/ExecutionEngine/MCJIT/MCJITTestBase.h	2014-12-02 16:51:19.000000000 -0800
-+++ unittests/ExecutionEngine/MCJIT/MCJITTestBase.h	2016-01-23 11:13:10.000000000 -0800
-@@ -71,8 +71,8 @@
-     SmallVector<Value*, 1> CallArgs;
- 
-     Function::arg_iterator arg_iter = Result->arg_begin();
--    for(;arg_iter != Result->arg_end(); ++arg_iter)
--      CallArgs.push_back(arg_iter);
-+    for (Argument &A : Result->args())
-+      CallArgs.push_back(&A);
- 
-     Value *ReturnCode = Builder.CreateCall(Callee, CallArgs);
-     Builder.CreateRet(ReturnCode);
-@@ -98,8 +98,8 @@
-     Function *Result = startFunction<int32_t(int32_t, int32_t)>(M, Name);
- 
-     Function::arg_iterator args = Result->arg_begin();
--    Value *Arg1 = args;
--    Value *Arg2 = ++args;
-+    Value *Arg1 = &*args;
-+    Value *Arg2 = &*++args;
-     Value *AddResult = Builder.CreateAdd(Arg1, Arg2);
- 
-     endFunctionWithRet(Result, AddResult);
-@@ -170,7 +170,7 @@
-     BasicBlock *RecursiveCase = BasicBlock::Create(Context, "", Result);
- 
-     // if (num == 0)
--    Value *Param = Result->arg_begin();
-+    Value *Param = &*Result->arg_begin();
-     Value *Zero = ConstantInt::get(Context, APInt(32, 0));
-     Builder.CreateCondBr(Builder.CreateICmpEQ(Param, Zero),
-                          BaseCase, RecursiveCase);
---- unittests/IR/DominatorTreeTest.cpp	2014-08-19 09:58:54.000000000 -0700
-+++ unittests/IR/DominatorTreeTest.cpp	2016-01-23 11:18:36.000000000 -0800
-@@ -31,29 +31,29 @@
-         PostDominatorTree *PDT = &getAnalysis<PostDominatorTree>();
-         Function::iterator FI = F.begin();
- 
--        BasicBlock *BB0 = FI++;
-+        BasicBlock *BB0 = &*FI++;
-         BasicBlock::iterator BBI = BB0->begin();
--        Instruction *Y1 = BBI++;
--        Instruction *Y2 = BBI++;
--        Instruction *Y3 = BBI++;
-+        Instruction *Y1 = &*BBI++;
-+        Instruction *Y2 = &*BBI++;
-+        Instruction *Y3 = &*BBI++;
- 
--        BasicBlock *BB1 = FI++;
-+        BasicBlock *BB1 = &*FI++;
-         BBI = BB1->begin();
--        Instruction *Y4 = BBI++;
-+        Instruction *Y4 = &*BBI++;
- 
--        BasicBlock *BB2 = FI++;
-+        BasicBlock *BB2 = &*FI++;
-         BBI = BB2->begin();
--        Instruction *Y5 = BBI++;
-+        Instruction *Y5 = &*BBI++;
- 
--        BasicBlock *BB3 = FI++;
-+        BasicBlock *BB3 = &*FI++;
-         BBI = BB3->begin();
--        Instruction *Y6 = BBI++;
--        Instruction *Y7 = BBI++;
-+        Instruction *Y6 = &*BBI++;
-+        Instruction *Y7 = &*BBI++;
- 
--        BasicBlock *BB4 = FI++;
-+        BasicBlock *BB4 = &*FI++;
-         BBI = BB4->begin();
--        Instruction *Y8 = BBI++;
--        Instruction *Y9 = BBI++;
-+        Instruction *Y8 = &*BBI++;
-+        Instruction *Y9 = &*BBI++;
- 
-         // Reachability
-         EXPECT_TRUE(DT->isReachableFromEntry(BB0));
---- unittests/IR/IRBuilderTest.cpp	2014-09-02 13:03:00.000000000 -0700
-+++ unittests/IR/IRBuilderTest.cpp	2016-01-23 11:19:43.000000000 -0800
-@@ -280,7 +280,7 @@
-   {
-     IRBuilder<>::InsertPointGuard Guard(Builder);
-     Builder.SetInsertPoint(cast<Instruction>(F));
--    EXPECT_EQ(F, Builder.GetInsertPoint());
-+    EXPECT_EQ(F, &*Builder.GetInsertPoint());
-   }
- 
-   EXPECT_EQ(BB->end(), Builder.GetInsertPoint());
---- unittests/IR/LegacyPassManagerTest.cpp	2014-09-10 14:27:43.000000000 -0700
-+++ unittests/IR/LegacyPassManagerTest.cpp	2016-01-23 11:21:26.000000000 -0800
-@@ -521,7 +521,7 @@
-       // Function: test4 (func_test4)
-       {
-         Function::arg_iterator args = func_test4->arg_begin();
--        Value* int1_f = args++;
-+        Value* int1_f = &*args++;
-         int1_f->setName("f");
- 
-         BasicBlock* label_entry_11 = BasicBlock::Create(getGlobalContext(), "entry",func_test4,nullptr);
---- unittests/IR/ValueTest.cpp	2014-10-23 07:45:19.000000000 -0700
-+++ unittests/IR/ValueTest.cpp	2016-01-23 11:23:38.000000000 -0800
-@@ -38,9 +38,9 @@
- 
-   Function *F = M->getFunction("f");
- 
--  EXPECT_FALSE(F->isUsedInBasicBlock(F->begin()));
--  EXPECT_TRUE((++F->arg_begin())->isUsedInBasicBlock(F->begin()));
--  EXPECT_TRUE(F->arg_begin()->isUsedInBasicBlock(F->begin()));
-+  EXPECT_FALSE(F->isUsedInBasicBlock(&F->front()));
-+  EXPECT_TRUE((++F->arg_begin())->isUsedInBasicBlock(&F->front()));
-+  EXPECT_TRUE(F->arg_begin()->isUsedInBasicBlock(&F->front()));
- }
- 
- TEST(GlobalTest, CreateAddressSpace) {
---- unittests/Linker/LinkModulesTest.cpp	2015-01-14 03:23:27.000000000 -0800
-+++ unittests/Linker/LinkModulesTest.cpp	2016-01-23 11:25:17.000000000 -0800
-@@ -73,7 +73,7 @@
- 
-   std::vector<Value *> GEPIndices;
-   GEPIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ctx), 0));
--  GEPIndices.push_back(F->arg_begin());
-+  GEPIndices.push_back(&*F->arg_begin());
- 
-   Value *GEP = Builder.CreateGEP(GV, GEPIndices, "switch.gep");
-   Value *Load = Builder.CreateLoad(GEP, "switch.load");
---- unittests/Support/Makefile	2013-08-01 11:42:28.000000000 -0700
-+++ unittests/Support/Makefile	2016-01-27 11:20:22.000000000 -0800
-@@ -13,3 +13,7 @@
- 
- include $(LEVEL)/Makefile.config
- include $(LLVM_SRC_ROOT)/unittests/Makefile.unittest
-+
-+C.Flags += -DALIAS_WITH_ARGUMENT_TESTS_ARE_BROKEN
-+CXX.Flags += -DALIAS_WITH_ARGUMENT_TESTS_ARE_BROKEN
-+
---- unittests/Transforms/Utils/Cloning.cpp	2015-01-14 03:23:27.000000000 -0800
-+++ unittests/Transforms/Utils/Cloning.cpp	2016-01-23 11:29:52.000000000 -0800
-@@ -165,7 +165,7 @@
- 
-   Attribute::AttrKind AK[] = { Attribute::NoCapture };
-   AttributeSet AS = AttributeSet::get(context, 0, AK);
--  Argument *A = F1->arg_begin();
-+  Argument *A = &*F1->arg_begin();
-   A->addAttr(AS);
- 
-   SmallVector<ReturnInst*, 4> Returns;
-@@ -193,7 +193,7 @@
- 
-   SmallVector<ReturnInst*, 4> Returns;
-   ValueToValueMapTy VMap;
--  VMap[F1->arg_begin()] = F2->arg_begin();
-+  VMap[&*F1->arg_begin()] = &*F2->arg_begin();
- 
-   CloneFunctionInto(F2, F1, VMap, false, Returns);
-   EXPECT_EQ(CallingConv::Cold, F2->getCallingConv());
---- unittests/Transforms/Utils/IntegerDivision.cpp	2013-11-18 22:54:19.000000000 -0800
-+++ unittests/Transforms/Utils/IntegerDivision.cpp	2016-01-23 11:32:46.000000000 -0800
-@@ -35,8 +35,8 @@
-   Builder.SetInsertPoint(BB);
- 
-   Function::arg_iterator AI = F->arg_begin();
--  Value *A = AI++;
--  Value *B = AI++;
-+  Value *A = &*AI++;
-+  Value *B = &*AI++;
- 
-   Value *Div = Builder.CreateSDiv(A, B);
-   EXPECT_TRUE(BB->front().getOpcode() == Instruction::SDiv);
-@@ -65,8 +65,8 @@
-   Builder.SetInsertPoint(BB);
- 
-   Function::arg_iterator AI = F->arg_begin();
--  Value *A = AI++;
--  Value *B = AI++;
-+  Value *A = &*AI++;
-+  Value *B = &*AI++;
- 
-   Value *Div = Builder.CreateUDiv(A, B);
-   EXPECT_TRUE(BB->front().getOpcode() == Instruction::UDiv);
-@@ -95,8 +95,8 @@
-   Builder.SetInsertPoint(BB);
- 
-   Function::arg_iterator AI = F->arg_begin();
--  Value *A = AI++;
--  Value *B = AI++;
-+  Value *A = &*AI++;
-+  Value *B = &*AI++;
- 
-   Value *Rem = Builder.CreateSRem(A, B);
-   EXPECT_TRUE(BB->front().getOpcode() == Instruction::SRem);
-@@ -125,8 +125,8 @@
-   Builder.SetInsertPoint(BB);
- 
-   Function::arg_iterator AI = F->arg_begin();
--  Value *A = AI++;
--  Value *B = AI++;
-+  Value *A = &*AI++;
-+  Value *B = &*AI++;
- 
-   Value *Rem = Builder.CreateURem(A, B);
-   EXPECT_TRUE(BB->front().getOpcode() == Instruction::URem);
-@@ -156,8 +156,8 @@
-   Builder.SetInsertPoint(BB);
- 
-   Function::arg_iterator AI = F->arg_begin();
--  Value *A = AI++;
--  Value *B = AI++;
-+  Value *A = &*AI++;
-+  Value *B = &*AI++;
- 
-   Value *Div = Builder.CreateSDiv(A, B);
-   EXPECT_TRUE(BB->front().getOpcode() == Instruction::SDiv);
-@@ -186,8 +186,8 @@
-   Builder.SetInsertPoint(BB);
- 
-   Function::arg_iterator AI = F->arg_begin();
--  Value *A = AI++;
--  Value *B = AI++;
-+  Value *A = &*AI++;
-+  Value *B = &*AI++;
- 
-   Value *Div = Builder.CreateUDiv(A, B);
-   EXPECT_TRUE(BB->front().getOpcode() == Instruction::UDiv);
-@@ -216,8 +216,8 @@
-   Builder.SetInsertPoint(BB);
- 
-   Function::arg_iterator AI = F->arg_begin();
--  Value *A = AI++;
--  Value *B = AI++;
-+  Value *A = &*AI++;
-+  Value *B = &*AI++;
- 
-   Value *Rem = Builder.CreateSRem(A, B);
-   EXPECT_TRUE(BB->front().getOpcode() == Instruction::SRem);
-@@ -246,8 +246,8 @@
-   Builder.SetInsertPoint(BB);
- 
-   Function::arg_iterator AI = F->arg_begin();
--  Value *A = AI++;
--  Value *B = AI++;
-+  Value *A = &*AI++;
-+  Value *B = &*AI++;
- 
-   Value *Rem = Builder.CreateURem(A, B);
-   EXPECT_TRUE(BB->front().getOpcode() == Instruction::URem);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/021-solaris-LLVM-tools-llc.patch	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,33 @@
+# 24314638 LLVM CommandLine subsystem is busted
+# 3.9.X for upstream.
+--- tools/llc/llc.cpp	2015-12-07 14:21:39.000000000 -0500
++++ tools/llc/llc.cpp	2016-05-08 23:19:20.578431871 -0400
+@@ -54,13 +54,14 @@
+ // and back-end code generation options are specified with the target machine.
+ //
+ static cl::opt<std::string>
+-InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
++InputFilename(cl::Positional, cl::desc("<input bitcode>"),
++              cl::init(std::string("-")));
+ 
+ static cl::opt<std::string>
+ OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
+ 
+ static cl::opt<unsigned>
+-TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
++TimeCompilations("time-compilations", cl::Hidden, cl::init(1U),
+                  cl::value_desc("N"),
+                  cl::desc("Repeat compilation N times for timing"));
+ 
+@@ -74,8 +75,9 @@
+          cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
+                   "(default = '-O2')"),
+          cl::Prefix,
+-         cl::ZeroOrMore,
+-         cl::init(' '));
++         cl::Optional,
++         cl::ValueRequired,
++         cl::init('2'));
+ 
+ static cl::opt<std::string>
+ TargetTriple("mtriple", cl::desc("Override target triple for module"));
--- a/components/llvm/patches/022-google-test-harness-22643565.patch	Thu Jul 28 16:15:45 2016 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,67 +0,0 @@
-# - 22643565 - llvm's Google test harness needs some attention
-# For upstream - maytbe.
---- utils/unittest/googletest/src/gtest-port.cc	2013-11-18 16:57:56.000000000 -0800
-+++ utils/unittest/googletest/src/gtest-port.cc	2016-02-01 11:34:55.170628325 -0800
-@@ -51,6 +51,13 @@
- # include <mach/vm_map.h>
- #endif  // GTEST_OS_MAC
- 
-+#if GTEST_OS_SOLARIS
-+# include <strings.h>
-+# include <sys/types.h>
-+# include <dirent.h>
-+# include <unistd.h>
-+#endif
-+
- #include "gtest/gtest-spi.h"
- #include "gtest/gtest-message.h"
- #include "gtest/internal/gtest-internal.h"
-@@ -101,9 +108,36 @@
- #else
- 
- size_t GetThreadCount() {
-+  size_t NumThreads = 1U;
-+
-+#if GTEST_OS_SOLARIS
-+  char lwpdir[PATH_MAX+1];
-+  (void) std::memset(lwpdir, 0, sizeof(lwpdir));
-+  (void) std::sprintf(lwpdir, "/proc/%i/lwp/", static_cast<int>(getpid()));
-+
-+  struct dirent *DE;
-+  DIR *D = ::opendir(lwpdir);
-+  if (!D)
-+    return NumThreads;
-+
-+  while ((DE = ::readdir(D)) != NULL) {
-+    if (DE->d_name[0] == '.') {
-+      if ((DE->d_name[1] == '\0') ||
-+          ((DE->d_name[1] == '.') && (DE->d_name[2] == '\0')))
-+        continue;
-+    }
-+
-+    NumThreads =
-+      static_cast<size_t>(std::max<int>(NumThreads, std::atoi(DE->d_name)));
-+  }
-+
-+  ::rewinddir(D);
-+  ::closedir(D);
-+#endif
-+
-   // There's no portable way to detect the number of threads, so we just
-   // return 0 to indicate that we cannot detect it.
--  return 0;
-+  return NumThreads;
- }
- 
- #endif  // GTEST_OS_MAC
---- utils/unittest/googletest/include/gtest/internal/gtest-port.h	2014-02-19 07:18:30.000000000 -0800
-+++ utils/unittest/googletest/include/gtest/internal/gtest-port.h	2016-02-01 11:15:20.899289723 -0800
-@@ -238,7 +238,7 @@
- # endif  // ANDROID
- #elif defined __MVS__
- # define GTEST_OS_ZOS 1
--#elif defined(__sun) && defined(__SVR4)
-+#elif (defined(__sun) || defined(__sun__)) && defined(__SVR4)
- # define GTEST_OS_SOLARIS 1
- #elif defined(_AIX)
- # define GTEST_OS_AIX 1
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/022-solaris-LLVM-tools-llvm-as.patch	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,29 @@
+# 24314638 LLVM CommandLine subsystem is busted
+# 3.9.X for upstream.
+--- tools/llvm-as/llvm-as.cpp	2015-10-04 10:33:43.000000000 -0400
++++ tools/llvm-as/llvm-as.cpp	2016-05-08 23:19:20.579431896 -0400
+@@ -28,15 +28,21 @@
+ #include "llvm/Support/SourceMgr.h"
+ #include "llvm/Support/SystemUtils.h"
+ #include "llvm/Support/ToolOutputFile.h"
+-#include <memory>
+ using namespace llvm;
+ 
++#include <memory>
++#include <string>
++
+ static cl::opt<std::string>
+-InputFilename(cl::Positional, cl::desc("<input .llvm file>"), cl::init("-"));
++InputFilename(cl::Positional, cl::desc("<input file>"),
++              cl::NotHidden,
++              cl::Optional,
++              cl::init(std::string("-")),
++              cl::ValuePositionalNoArgs);
+ 
+ static cl::opt<std::string>
+ OutputFilename("o", cl::desc("Override output filename"),
+-               cl::value_desc("filename"));
++               cl::value_desc("<output filename>"));
+ 
+ static cl::opt<bool>
+ Force("f", cl::desc("Enable binary output on terminals"));
--- a/components/llvm/patches/023-Makefile.config.in.patch	Thu Jul 28 16:15:45 2016 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,48 +0,0 @@
-# ${prefix/libdir must be set correctly for 64-bit builds.
-# We can't have $ORIGIN in RPATH/RUNPATH.
-# Not for upstream. The autoconf-based build system is removed in 3.8.X.
---- Makefile.config.in	2016-02-02 09:12:17.972038970 -0800
-+++ Makefile.config.in	2016-02-02 09:46:11.950055804 -0800
-@@ -13,6 +13,10 @@
- #===------------------------------------------------------------------------===#
- 
- MACH = $(shell uname -p)
-+MACH64=sparcv9
-+ifeq ($(MACH),i386)
-+  MACH64=amd64
-+endif
- 
- # Define LLVM specific info and directories based on the autoconf variables
- LLVMPackageName   := @PACKAGE_TARNAME@
-@@ -182,6 +186,10 @@
- # Path to the nm program
- NM_PATH = @NM@
- 
-+ifeq ($(findstring -m32,$(CXXFLAGS)),)
-+  PROJ_libdir = $(PROJ_prefix)/lib/$(MACH64)
-+endif
-+
- # The pathnames of the programs we require to build
- CMP        := @CMP@
- CP         := @CP@
---- Makefile.rules	2016-02-02 09:59:19.111715578 -0800
-+++ Makefile.rules	2016-02-02 11:51:02.057248471 -0800
-@@ -604,7 +604,7 @@
- endif
- 
- ifdef SHARED_LIBRARY
--ifneq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW))
-+ifneq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW SunOS))
- ifneq ($(HOST_OS),Darwin)
-   LD.Flags += $(RPATH) -Wl,'$$ORIGIN'
- else
-@@ -665,7 +665,9 @@
-   endif
-   ifneq ($(HOST_OS), Darwin)
-     ifdef TOOLNAME
-+      ifneq ($(HOST_OS), $(filter $(HOST_OS), SunOS))
-       LD.Flags += $(RPATH) -Wl,'$$ORIGIN/../lib'
-+      endif
-       ifeq ($(HOST_OS), $(filter $(HOST_OS), SunOS))
-         LD.Flags += -Wl,-z -Wl,discard-unused=sections
-         LD.Flags += -Wl,-M -Wl,$(PROJ_SRC_ROOT)/mapfiles/map.gnu-sections
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/023-solaris-LLVM-tools-llvm-config.patch	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,14 @@
+# Miscellaneous fixes for Solaris.
+# 3.9.X upstream.
+--- tools/llvm-config/llvm-config.cpp	2016-01-12 02:23:58.000000000 -0500
++++ tools/llvm-config/llvm-config.cpp	2016-05-23 12:20:06.121494348 -0400
+@@ -440,6 +440,9 @@
+       } else if (Arg == "--cxxflags") {
+         OS << ActiveIncludeOption << ' ' << LLVM_CXXFLAGS << '\n';
+       } else if (Arg == "--ldflags") {
++        if (HostTriple.isOSSolaris())
++          OS << LLVM_LDFLAGS << '\n';
++        else
+         OS << "-L" << ActiveLibDir << ' ' << LLVM_LDFLAGS << '\n';
+       } else if (Arg == "--system-libs") {
+         PrintSystemLibs = true;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/024-solaris-LLVM-tools-llvm-dis.patch	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,19 @@
+# 24314638 LLVM CommandLine subsystem is busted
+# 3.9.X upstream.
+--- tools/llvm-dis/llvm-dis.cpp	2015-12-18 15:13:39.000000000 -0500
++++ tools/llvm-dis/llvm-dis.cpp	2016-05-08 23:19:20.579431896 -0400
+@@ -38,11 +38,12 @@
+ using namespace llvm;
+ 
+ static cl::opt<std::string>
+-InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
++InputFilename(cl::Positional, cl::desc("<input bitcode>"),
++              cl::init(std::string("-")));
+ 
+ static cl::opt<std::string>
+ OutputFilename("o", cl::desc("Override output filename"),
+-               cl::value_desc("filename"));
++               cl::value_desc("<output filename>"));
+ 
+ static cl::opt<bool>
+ Force("f", cl::desc("Enable binary output on terminals"));
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/025-solaris-LLVM-tools-opt.patch	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,202 @@
+# 24314638 LLVM CommandLine subsystem is busted
+# 3.9.X for upstream.
+--- tools/opt/opt.cpp	2015-12-04 16:38:12.000000000 -0900
++++ tools/opt/opt.cpp	2016-07-06 13:46:06.903114750 -0800
+@@ -67,16 +67,16 @@
+ // to run over the module. This flag switches opt to use the new pass manager
+ // infrastructure, completely disabling all of the flags specific to the old
+ // pass management.
+-static cl::opt<std::string> PassPipeline(
+-    "passes",
+-    cl::desc("A textual description of the pass pipeline for optimizing"),
+-    cl::Hidden);
++static cl::opt<std::string>
++PassPipeline("passes",
++             cl::desc("A textual description of the pass pipeline for optimizing"),
++             cl::Hidden);
+ 
+ // Other command line options...
+ //
+ static cl::opt<std::string>
+ InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
+-    cl::init("-"), cl::value_desc("filename"));
++    cl::init(std::string("-")), cl::value_desc("filename"));
+ 
+ static cl::opt<std::string>
+ OutputFilename("o", cl::desc("Override output filename"),
+@@ -116,25 +116,54 @@
+ StandardLinkOpts("std-link-opts",
+                  cl::desc("Include the standard link time optimizations"));
+ 
+-static cl::opt<bool>
++static cl::opt<char>
++OptLevel("O",
++         cl::desc("Optimization level. [-O1, -O2, -Os, -Oz or -O3] "
++                  "(default = '-O2')"),
++         cl::Prefix,
++         cl::Optional,
++         cl::ValueRequired,
++         cl::init('2'));
++
++static cl::opt<char>
+ OptLevelO1("O1",
+-           cl::desc("Optimization level 1. Similar to clang -O1"));
++           cl::desc("Optimization level 1. Similar to clang -O1"),
++           cl::Prefix,
++           cl::Optional,
++           cl::ValueRequired,
++           cl::init('0'));
+ 
+-static cl::opt<bool>
++static cl::opt<char>
+ OptLevelO2("O2",
+-           cl::desc("Optimization level 2. Similar to clang -O2"));
++           cl::desc("Optimization level 2. Similar to clang -O2"),
++           cl::Prefix,
++           cl::Optional,
++           cl::ValueRequired,
++           cl::init('0'));
+ 
+-static cl::opt<bool>
++static cl::opt<char>
+ OptLevelOs("Os",
+-           cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os"));
++           cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os"),
++           cl::Prefix,
++           cl::Optional,
++           cl::ValueRequired,
++           cl::init('0'));
+ 
+-static cl::opt<bool>
++static cl::opt<char>
+ OptLevelOz("Oz",
+-           cl::desc("Like -Os but reduces code size further. Similar to clang -Oz"));
++           cl::desc("Like -Os but reduces code size further. Similar to clang -Oz"),
++           cl::Prefix,
++           cl::Optional,
++           cl::ValueRequired,
++           cl::init('0'));
+ 
+-static cl::opt<bool>
++static cl::opt<char>
+ OptLevelO3("O3",
+-           cl::desc("Optimization level 3. Similar to clang -O3"));
++           cl::desc("Optimization level 3. Similar to clang -O3"),
++           cl::Prefix,
++           cl::Optional,
++           cl::ValueRequired,
++           cl::init('0'));
+ 
+ static cl::opt<std::string>
+ TargetTriple("mtriple", cl::desc("Override target triple for module"));
+@@ -158,7 +187,6 @@
+                         cl::desc("Disable the slp vectorization pass"),
+                         cl::init(false));
+ 
+-
+ static cl::opt<bool>
+ DisableSimplifyLibCalls("disable-simplify-libcalls",
+                         cl::desc("Disable simplify-libcalls"));
+@@ -179,7 +207,7 @@
+ static cl::opt<std::string>
+ DefaultDataLayout("default-data-layout",
+           cl::desc("data layout string to use if not specified by module"),
+-          cl::value_desc("layout-string"), cl::init(""));
++          cl::value_desc("layout-string"), cl::init(std::string("")));
+ 
+ static cl::opt<bool> PreserveBitcodeUseListOrder(
+     "preserve-bc-uselistorder",
+@@ -208,37 +236,37 @@
+ /// This routine adds optimization passes based on selected optimization level,
+ /// OptLevel.
+ ///
+-/// OptLevel - Optimization Level
++/// OptimLevel - Optimization Level
+ static void AddOptimizationPasses(legacy::PassManagerBase &MPM,
+                                   legacy::FunctionPassManager &FPM,
+-                                  unsigned OptLevel, unsigned SizeLevel) {
++                                  unsigned OptimLevel, unsigned SizeLevel) {
+   FPM.add(createVerifierPass()); // Verify that input is correct
+ 
+   PassManagerBuilder Builder;
+-  Builder.OptLevel = OptLevel;
++  Builder.OptLevel = OptimLevel;
+   Builder.SizeLevel = SizeLevel;
+ 
+   if (DisableInline) {
+     // No inlining pass
+-  } else if (OptLevel > 1) {
+-    Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel);
++  } else if (OptimLevel > 1) {
++    Builder.Inliner = createFunctionInliningPass(OptimLevel, SizeLevel);
+   } else {
+     Builder.Inliner = createAlwaysInlinerPass();
+   }
+   Builder.DisableUnitAtATime = !UnitAtATime;
+   Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ?
+-                               DisableLoopUnrolling : OptLevel == 0;
++                               DisableLoopUnrolling : OptimLevel == 0;
+ 
+   // This is final, unless there is a #pragma vectorize enable
+   if (DisableLoopVectorization)
+     Builder.LoopVectorize = false;
+   // If option wasn't forced via cmd line (-vectorize-loops, -loop-vectorize)
+   else if (!Builder.LoopVectorize)
+-    Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2;
++    Builder.LoopVectorize = OptimLevel > 1 && SizeLevel < 2;
+ 
+   // When #pragma vectorize is on for SLP, do the same as above
+   Builder.SLPVectorize =
+-      DisableSLPVectorization ? false : OptLevel > 1 && SizeLevel < 2;
++      DisableSLPVectorization ? false : OptimLevel > 1 && SizeLevel < 2;
+ 
+   Builder.populateFunctionPassManager(FPM);
+   Builder.populateModulePassManager(MPM);
+@@ -260,11 +288,11 @@
+ //
+ 
+ static CodeGenOpt::Level GetCodeGenOptLevel() {
+-  if (OptLevelO1)
++  if (OptLevelO1.getValue())
+     return CodeGenOpt::Less;
+-  if (OptLevelO2)
++  if (OptLevelO2.getValue())
+     return CodeGenOpt::Default;
+-  if (OptLevelO3)
++  if (OptLevelO3.getValue())
+     return CodeGenOpt::Aggressive;
+   return CodeGenOpt::None;
+ }
+@@ -492,27 +520,27 @@
+ 
+     if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
+       AddOptimizationPasses(Passes, *FPasses, 1, 0);
+-      OptLevelO1 = false;
++      OptLevelO1.setValue(false);
+     }
+ 
+     if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
+       AddOptimizationPasses(Passes, *FPasses, 2, 0);
+-      OptLevelO2 = false;
++      OptLevelO2.setValue(false);
+     }
+ 
+     if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
+       AddOptimizationPasses(Passes, *FPasses, 2, 1);
+-      OptLevelOs = false;
++      OptLevelOs.setValue(false);
+     }
+ 
+     if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
+       AddOptimizationPasses(Passes, *FPasses, 2, 2);
+-      OptLevelOz = false;
++      OptLevelOz.setValue(false);
+     }
+ 
+     if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
+       AddOptimizationPasses(Passes, *FPasses, 3, 0);
+-      OptLevelO3 = false;
++      OptLevelO3.setValue(false);
+     }
+ 
+     const PassInfo *PassInf = PassList[i];
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/026-solaris-LLVM-tools-bugpoint.patch	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,28 @@
+# 24314638 LLVM CommandLine subsystem is busted
+# 3.9.X for upstream.
+--- tools/bugpoint/OptimizerDriver.cpp	2015-04-14 23:14:06.000000000 -0400
++++ tools/bugpoint/OptimizerDriver.cpp	2016-05-08 23:19:20.539430923 -0400
+@@ -47,14 +47,15 @@
+     cl::desc("Preserve use-list order when writing LLVM bitcode."),
+     cl::init(true), cl::Hidden);
+ 
+-namespace {
+-  // ChildOutput - This option captures the name of the child output file that
+-  // is set up by the parent bugpoint process
+-  cl::opt<std::string> ChildOutput("child-output", cl::ReallyHidden);
+-  cl::opt<std::string> OptCmd("opt-command", cl::init(""),
+-                              cl::desc("Path to opt. (default: search path "
+-                                       "for 'opt'.)"));
+-}
++// ChildOutput - This option captures the name of the child output file that
++// is set up by the parent bugpoint process
++static cl::opt<std::string>
++ChildOutput("child-output", cl::ReallyHidden);
++
++static cl::opt<std::string>
++OptCmd("opt-command", cl::init(std::string("")),
++       cl::desc("Path to opt. (default: search path "
++                "for 'opt'.)"));
+ 
+ /// writeProgramToFile - This writes the current "Program" to the named bitcode
+ /// file.  If an error occurs, true is returned.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/027-solaris-LLVM-libsupport-unittests.patch	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,172 @@
+# 24314638 LLVM CommandLine subsystem is busted
+# 3.9.X for upstream. Command Aliasing is still broken.
+--- unittests/Support/CommandLineTest.cpp	2015-11-17 11:00:52.000000000 -0800
++++ unittests/Support/CommandLineTest.cpp	2016-05-14 18:05:59.835319423 -0700
+@@ -7,13 +7,23 @@
+ //
+ //===----------------------------------------------------------------------===//
+ 
++#ifndef SKIP_ENVIRONMENT_TESTS
++#define SKIP_ENVIRONMENT_TESTS 1
++#endif
++
++#if defined(__sun) || defined(__sun__)
++#define ALIAS_WITH_ARGUMENT_TESTS_ARE_BROKEN 1
++#endif
++
+ #include "llvm/ADT/STLExtras.h"
+ #include "llvm/Config/config.h"
+ #include "llvm/Support/CommandLine.h"
+ #include "llvm/Support/StringSaver.h"
+ #include "gtest/gtest.h"
++
+ #include <stdlib.h>
+ #include <string>
++#include <vector>
+ 
+ using namespace llvm;
+ 
+@@ -48,25 +58,30 @@
+ template <typename T>
+ class StackOption : public cl::opt<T> {
+   typedef cl::opt<T> Base;
++
+ public:
+   // One option...
+-  template<class M0t>
+-  explicit StackOption(const M0t &M0) : Base(M0) {}
++  template<typename M0t>
++  explicit StackOption(const M0t &M0)
++  : cl::opt<T>(M0) { }
+ 
+   // Two options...
+-  template<class M0t, class M1t>
+-  StackOption(const M0t &M0, const M1t &M1) : Base(M0, M1) {}
++  template<typename M0t, typename M1t>
++  explicit StackOption(const M0t &M0, const M1t &M1)
++  : cl::opt<T>(M0, M1) { }
+ 
+   // Three options...
+-  template<class M0t, class M1t, class M2t>
+-  StackOption(const M0t &M0, const M1t &M1, const M2t &M2) : Base(M0, M1, M2) {}
++  template<typename M0t, typename M1t, typename M2t>
++  explicit StackOption(const M0t &M0, const M1t &M1, const M2t &M2)
++  : cl::opt<T>(M0, M1, M2) { }
+ 
+   // Four options...
+-  template<class M0t, class M1t, class M2t, class M3t>
+-  StackOption(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3)
+-    : Base(M0, M1, M2, M3) {}
++  template<typename M0t, typename M1t, typename M2t, typename M3t>
++  explicit StackOption(const M0t &M0, const M1t &M1, const M2t &M2,
++                       const M3t &M3)
++  : cl::opt<T>(M0, M1, M2, M3) { }
+ 
+-  ~StackOption() override { this->removeArgument(); }
++  ~StackOption<T>() override { this->removeArgument(); }
+ };
+ 
+ 
+@@ -94,15 +109,15 @@
+     "Failed to modify option's option category.";
+ 
+   Retrieved->setDescription(Description);
+-  ASSERT_STREQ(Retrieved->HelpStr.data(), Description)
++  ASSERT_STREQ(Retrieved->HelpStr, Description)
+       << "Changing option description failed.";
+ 
+   Retrieved->setArgStr(ArgString);
+-  ASSERT_STREQ(ArgString, Retrieved->ArgStr.data())
++  ASSERT_STREQ(ArgString, Retrieved->ArgStr)
+       << "Failed to modify option's Argument string.";
+ 
+   Retrieved->setValueStr(ValueString);
+-  ASSERT_STREQ(Retrieved->ValueStr.data(), ValueString)
++  ASSERT_STREQ(Retrieved->ValueStr, ValueString)
+       << "Failed to modify option's Value string.";
+ 
+   Retrieved->setHiddenFlag(cl::Hidden);
+@@ -113,7 +128,7 @@
+ 
+ const char test_env_var[] = "LLVM_TEST_COMMAND_LINE_FLAGS";
+ 
+-cl::opt<std::string> EnvironmentTestOption("env-test-opt");
++static cl::opt<std::string> EnvironmentTestOption("env-test-opt");
+ TEST(CommandLineTest, ParseEnvironment) {
+   TempEnvVar TEV(test_env_var, "-env-test-opt=hello");
+   EXPECT_EQ("", EnvironmentTestOption);
+@@ -148,12 +163,13 @@
+ }
+ 
+ typedef void ParserFunction(StringRef Source, StringSaver &Saver,
+-                            SmallVectorImpl<const char *> &NewArgv,
++                            std::vector<const char *> &NewArgv,
+                             bool MarkEOLs);
+ 
+ void testCommandLineTokenizer(ParserFunction *parse, const char *Input,
+-                              const char *const Output[], size_t OutputSize) {
+-  SmallVector<const char *, 0> Actual;
++                              std::vector<const char*> &Output,
++                              size_t OutputSize) {
++  std::vector<const char *> Actual;
+   BumpPtrAllocator A;
+   StringSaver Saver(A);
+   parse(Input, Saver, Actual, /*MarkEOLs=*/false);
+@@ -170,7 +186,12 @@
+   const char *const Output[] = { "foo bar", "foo bar", "foo bar", "foo\\bar",
+                                  "foobarbaz", "C:\\src\\foo.cpp",
+                                  "C:\\src\\foo.cpp" };
+-  testCommandLineTokenizer(cl::TokenizeGNUCommandLine, Input, Output,
++
++  std::vector<const char*> OutputVector;
++  for (unsigned I = 0; I < array_lengthof(Output); ++I)
++    OutputVector.push_back(Output[I]);
++
++  testCommandLineTokenizer(cl::TokenizeGNUCommandLine, Input, OutputVector,
+                            array_lengthof(Output));
+ }
+ 
+@@ -179,10 +200,17 @@
+                       "\"st \\\"u\" \\v";
+   const char *const Output[] = { "a\\b", "c\\\\d", "e\\f g", "h\"i", "j\\\"k",
+                                  "lmn", "o", "pqr", "st \"u", "\\v" };
+-  testCommandLineTokenizer(cl::TokenizeWindowsCommandLine, Input, Output,
++
++  std::vector<const char*> OutputVector;
++  for (unsigned I = 0; I < array_lengthof(Output); ++I)
++    OutputVector.push_back(Output[I]);
++
++  testCommandLineTokenizer(cl::TokenizeWindowsCommandLine, Input, OutputVector,
+                            array_lengthof(Output));
+ }
+ 
++#ifndef ALIAS_WITH_ARGUMENT_TESTS_ARE_BROKEN
++// This test case is 100% broken.
+ TEST(CommandLineTest, AliasesWithArguments) {
+   static const size_t ARGC = 3;
+   const char *const Inputs[][ARGC] = {
+@@ -208,12 +236,12 @@
+ }
+ 
+ void testAliasRequired(int argc, const char *const *argv) {
+-  StackOption<std::string> Option("option", cl::Required);
+-  cl::alias Alias("o", llvm::cl::aliasopt(Option));
++  StackOption<std::string> O("option", cl::Required);
++  cl::alias Alias("o", llvm::cl::aliasopt(O));
+ 
+   cl::ParseCommandLineOptions(argc, argv);
+-  EXPECT_EQ("x", Option);
+-  EXPECT_EQ(1, Option.getNumOccurrences());
++  EXPECT_EQ("x", O);
++  EXPECT_EQ(1, O.getNumOccurrences());
+ 
+   Alias.removeArgument();
+ }
+@@ -224,6 +252,7 @@
+   testAliasRequired(array_lengthof(opts1), opts1);
+   testAliasRequired(array_lengthof(opts2), opts2);
+ }
++#endif
+ 
+ TEST(CommandLineTest, HideUnrelatedOptions) {
+   StackOption<int> TestOption1("hide-option-1");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/028-solaris-LLVM-libTableGen.patch	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,71 @@
+# 24314638 LLVM CommandLine subsystem is busted
+# 3.9.X for upstream.
+--- lib/TableGen/Main.cpp	2015-05-26 02:48:46.000000000 -0400
++++ lib/TableGen/Main.cpp	2016-05-08 23:19:20.537430874 -0400
+@@ -29,21 +29,39 @@
+ using namespace llvm;
+ 
+ static cl::opt<std::string>
+-OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"),
+-               cl::init("-"));
++OutputFilename(cl::Prefix, "o",
++               cl::desc("Output filename"),
++               cl::value_desc("filename"),
++               cl::NotHidden,
++               cl::Optional,
++               cl::init("-"),
++               cl::ValueRequired);
+ 
+ static cl::opt<std::string>
+-DependFilename("d",
++DependFilename(cl::Prefix, "d",
+                cl::desc("Dependency filename"),
+                cl::value_desc("filename"),
+-               cl::init(""));
++               cl::NotHidden,
++               cl::Optional,
++               cl::init(""),
++               cl::ValueRequired);
+ 
+ static cl::opt<std::string>
+-InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
++InputFilename(cl::Positional, "<input file>",
++              cl::desc("<input file>"),
++              cl::value_desc("Input filename"),
++              cl::NotHidden,
++              cl::Optional,
++              cl::init("-"),
++              cl::ValuePositionalNoArgs);
+ 
+ static cl::list<std::string>
+-IncludeDirs("I", cl::desc("Directory of include files"),
+-            cl::value_desc("directory"), cl::Prefix);
++IncludeDirs(cl::Prefix, "I",
++            cl::desc("Directory of include files"),
++            cl::value_desc("directory"),
++            cl::NotHidden,
++            cl::ZeroOrMore,
++            cl::ValueRequired);
+ 
+ /// \brief Create a dependency file for `-d` option.
+ ///
+@@ -74,8 +92,9 @@
+   RecordKeeper Records;
+ 
+   // Parse the input file.
++  llvm::Twine TFN(InputFilename);
+   ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
+-      MemoryBuffer::getFileOrSTDIN(InputFilename);
++      MemoryBuffer::getFileOrSTDIN(TFN);
+   if (std::error_code EC = FileOrErr.getError()) {
+     errs() << "Could not open input file '" << InputFilename
+            << "': " << EC.message() << "\n";
+@@ -87,7 +106,7 @@
+ 
+   // Record the location of the include directory so that the lexer can find
+   // it later.
+-  SrcMgr.setIncludeDirs(IncludeDirs);
++  SrcMgr.setIncludeDirs(IncludeDirs.getStorage());
+ 
+   TGParser Parser(SrcMgr, Records);
+ 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/029-solaris-LLVM-libTarget-X86.patch	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,53 @@
+# 22805043 implement the LLVM Intel Solaris native assembler
+# 3.9.X for upstream.
+--- lib/Target/X86/X86TargetMachine.cpp	2015-12-04 05:53:15.000000000 -0500
++++ lib/Target/X86/X86TargetMachine.cpp	2016-05-08 23:19:20.538430899 -0400
+@@ -50,6 +50,8 @@
+ 
+   if (TT.isOSLinux() || TT.isOSNaCl())
+     return make_unique<X86LinuxNaClTargetObjectFile>();
++  if (TT.isOSSolaris())
++    return make_unique<X86SolarisTargetObjectFile>();
+   if (TT.isOSBinFormatELF())
+     return make_unique<X86ELFTargetObjectFile>();
+   if (TT.isKnownWindowsMSVCEnvironment() || TT.isWindowsCoreCLREnvironment())
+--- lib/Target/X86/X86TargetObjectFile.cpp	2015-09-03 12:41:50.000000000 -0400
++++ lib/Target/X86/X86TargetObjectFile.cpp	2016-05-08 23:19:20.538430899 -0400
+@@ -67,6 +67,19 @@
+ }
+ 
+ void
++X86SolarisTargetObjectFile::Initialize(MCContext &Ctx,
++                                       const TargetMachine &TM) {
++  TargetLoweringObjectFileELF::Initialize(Ctx, TM);
++  InitializeELF(true);
++}
++
++const MCExpr *
++X86SolarisTargetObjectFile::getDebugThreadLocalSymbol(
++  const MCSymbol *Sym) const {
++  return MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_DTPOFF,
++                                 getContext());
++}
++void
+ X86LinuxNaClTargetObjectFile::Initialize(MCContext &Ctx,
+                                          const TargetMachine &TM) {
+   TargetLoweringObjectFileELF::Initialize(Ctx, TM);
+--- lib/Target/X86/X86TargetObjectFile.h	2015-07-16 02:04:17.000000000 -0400
++++ lib/Target/X86/X86TargetObjectFile.h	2016-05-08 23:19:20.538430899 -0400
+@@ -50,6 +50,15 @@
+     void Initialize(MCContext &Ctx, const TargetMachine &TM) override;
+   };
+ 
++  /// X86SolarisTargetObjectFile - This implementation is used for Solaris
++  /// x86 and x86-64.
++  class X86SolarisTargetObjectFile : public TargetLoweringObjectFileELF {
++    void Initialize(MCContext &Ctx, const TargetMachine &TM) override;
++
++    /// \brief Describe a TLS variable address within debug info.
++    const MCExpr *getDebugThreadLocalSymbol(const MCSymbol *Sym) const override;
++  };
++
+   /// \brief This implementation is used for Windows targets on x86 and x86-64.
+   class X86WindowsTargetObjectFile : public TargetLoweringObjectFileCOFF {
+     const MCExpr *
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/030-solaris-exception-demo.patch	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,17 @@
+# Miscellaneous fixes.
+# Not for upstream, because we only build this in DEBUG mode
+# and we neve package it.
+--- examples/ExceptionDemo/ExceptionDemo.cpp	2015-09-18 14:15:45.000000000 -0700
++++ examples/ExceptionDemo/ExceptionDemo.cpp	2016-05-11 18:59:34.443949997 -0700
+@@ -233,8 +233,9 @@
+        i != theArgNames.size();
+        ++argIndex, ++i) {
+ 
+-    argIndex->setName(theArgNames[i]);
+-    namedValues[theArgNames[i]] = argIndex;
++    std::string Name = theArgNames[i];
++    argIndex->setName(Name);
++    namedValues[Name] = &*argIndex;
+   }
+ 
+   return(ret);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/031-solaris-build-system.patch	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,1257 @@
+# 24314621 LLVM should build using the new CMake based build system
+# CMake parts for upstream, Solaris-specific parts no.
+--- Makefile.config.in	2015-08-07 12:44:47.000000000 -0400
++++ Makefile.config.in	2016-05-08 23:19:20.538430899 -0400
+@@ -12,6 +12,12 @@
+ #
+ #===------------------------------------------------------------------------===#
+ 
++MACH = $(shell uname -p)
++MACH64=sparcv9
++ifeq ($(MACH),i386)
++  MACH64=amd64
++endif
++
+ # Define LLVM specific info and directories based on the autoconf variables
+ LLVMPackageName   := @PACKAGE_TARNAME@
+ LLVMVersion       := @PACKAGE_VERSION@
+@@ -185,6 +191,11 @@
+ # Path to the nm program
+ NM_PATH = @NM@
+ 
++# Solaris-specific filesystem locations
++ifeq ($(findstring m32,$(CXXFLAGS)),)
++  PROJ_libdir = $(PROJ_prefix)/lib/$(MACH64)
++endif
++
+ # The pathnames of the programs we require to build
+ CMP        := @CMP@
+ CP         := @CP@
+@@ -225,6 +236,12 @@
+ 
+ LIBS       := @LIBS@
+ 
++ifeq ($(HOST_OS), $(filter $(HOST_OS), SunOS))
++  ifeq ($(MACH),sparc)
++    LIBS += -lkstat
++  endif
++endif
++
+ # Targets that are possible to build
+ ALL_TARGETS := @ALL_TARGETS@
+ 
+@@ -347,14 +364,14 @@
+ ENABLE_EMBED_STDCXX := @ENABLE_EMBED_STDCXX@
+ 
+ # Use -fvisibility-inlines-hidden?
+-ENABLE_VISIBILITY_INLINES_HIDDEN := @ENABLE_VISIBILITY_INLINES_HIDDEN@
++ENABLE_VISIBILITY_INLINES_HIDDEN := 0
+ 
+ # 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
++VERBOSE := 1
+ 
+ # Enable JIT for this platform
+ TARGET_HAS_JIT = @TARGET_HAS_JIT@
+###
+--- Makefile.rules	2015-11-09 08:10:00.000000000 -0800
++++ Makefile.rules	2016-05-28 17:08:22.413887137 -0700
+@@ -291,8 +291,8 @@
+   LD.Flags  += $(OPTIMIZE_OPTION)
+   ifdef DEBUG_SYMBOLS
+     BuildMode := $(BuildMode)+Debug
+-    CXX.Flags += -g
+-    C.Flags   += -g
++    CXX.Flags += -g3
++    C.Flags   += -g3
+     KEEP_SYMBOLS := 1
+   endif
+ else
+@@ -307,8 +307,8 @@
+     CXX.Flags += -gsplit-dwarf
+     C.Flags   += -gsplit-dwarf
+     else
+-    CXX.Flags += -g
+-    C.Flags   += -g
++    CXX.Flags += -g3
++    C.Flags   += -g3
+     endif
+     KEEP_SYMBOLS := 1
+   endif
+@@ -331,6 +331,13 @@
+  endif
+ endif
+ 
++ifeq ($(HOST_OS), $(filter $(HOST_OS), SunOS))
++  REQUIRES_EH := 1
++  REQUIRES_FRAME_POINTER := 1
++else
++  REQUIRES_EH := 0
++endif
++
+ ifeq ($(ENABLE_WERROR),1)
+   CXX.Flags += -Werror
+   C.Flags += -Werror
+@@ -355,14 +362,16 @@
+ endif
+ 
+ # IF REQUIRES_EH=1 is specified then don't disable exceptions
+-ifndef REQUIRES_EH
++ifneq ($(REQUIRES_EH), 1)
+   CXX.Flags += -fno-exceptions
++  REQUIRES_RTTI := 0
+ else
+   # If the library requires EH, it also requires RTTI.
++  CXX.Flags += -fexceptions
+   REQUIRES_RTTI := 1
+ endif
+ 
+-ifdef REQUIRES_FRAME_POINTER
++ifeq ($(REQUIRES_FRAME_POINTER), 1)
+   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))
+@@ -371,6 +380,8 @@
+ # If REQUIRES_RTTI=1 is specified then don't disable run-time type id.
+ ifneq ($(REQUIRES_RTTI), 1)
+   CXX.Flags += -fno-rtti
++else
++  CXX.Flags += -frtti
+ endif
+ 
+ ifeq ($(ENABLE_COVERAGE),1)
+@@ -596,7 +607,7 @@
+ endif
+ 
+ ifdef SHARED_LIBRARY
+-ifneq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW))
++ifneq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW SunOS))
+ ifneq ($(HOST_OS),Darwin)
+   LD.Flags += $(RPATH) -Wl,'$$ORIGIN'
+ else
+@@ -646,9 +657,13 @@
+     ifeq ($(HOST_OS),SunOS)
+       LD.Flags += -Wl,-z -Wl,discard-unused=sections
+     else
+-      ifneq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW))
++      ifneq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW SunOS))
+         LD.Flags += -Wl,--gc-sections
+       endif
++      ifeq ($(HOST_OS), $(filter $(HOST_OS), SunOS))
++	LD.Flags += -Wl,-z -Wl,discard-unused=sections
++	LD.Flags += -Wl,-M -Wl,$(PROJ_SRC_ROOT)/mapfiles/map.gnu-sections
++      endif
+     endif
+   endif
+ endif
+@@ -660,8 +675,14 @@
+   endif
+   ifneq ($(HOST_OS), Darwin)
+     ifdef TOOLNAME
++      ifneq ($(HOST_OS), $(filter $(HOST_OS), SunOS))
+       LD.Flags += $(RPATH) -Wl,'$$ORIGIN/../lib'
+     endif
++      ifeq ($(HOST_OS), $(filter $(HOST_OS), SunOS))
++	LD.Flags += -Wl,-z -Wl,discard-unused=sections
++	LD.Flags += -Wl,-M -Wl,$(PROJ_SRC_ROOT)/mapfiles/map.gnu-sections
++      endif
++    endif
+   else
+     ifneq ($(DARWIN_MAJVERS),4)
+       LD.Flags += $(RPATH) -Wl,@executable_path/../lib
+@@ -1105,6 +1126,18 @@
+ clean-local::
+ 	-$(Verb) $(RM) -f $(NativeExportsFile)
+ else
++ifeq ($(HOST_OS), $(filter $(HOST_OS), SunOS))
++# Solaris ld requires a version script rather than a plain list.
++NativeExportsFile := $(ObjDir)/$(notdir $(EXPORTED_SYMBOL_FILE)).map
++$(NativeExportsFile): $(EXPORTED_SYMBOL_FILE) $(ObjDir)/.dir
++    $(Verb) echo "{" > $@
++    $(Verb) ggrep -q '[[:alnum:]_]' $< && echo "  global:" >> $@ || :
++    $(Verb) gsed -e 's/$$/;/' -e 's/^/    /' < $< >> $@
++    $(Verb) echo "  local: *;" >> $@
++    $(Verb) echo "};" >> $@
++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
+@@ -1134,6 +1167,7 @@
+ endif
+ endif
+ endif
++endif
+ 
+ # Now add the linker command-line options to use the native export file.
+ 
+@@ -1153,6 +1187,11 @@
+ SharedLinkOptions += $(NativeExportsFile)
+ endif
+ 
++# Solaris
++ifeq ($(HOST_OS), $(filter $(HOST_OS), SunOS))
++LLVMLibsOptions += -Wl,-M -Wl,$(NativeExportsFile)
++endif
++
+ endif
+ 
+ ###############################################################################
+###
+--- lib/Support/CMakeLists.txt	2015-12-14 16:59:19.000000000 -0800
++++ lib/Support/CMakeLists.txt	2016-07-11 13:59:48.145404115 -0700
+@@ -28,6 +28,16 @@
+   endif( MINGW )
+ endif( NOT MSVC )
+ 
++# On Solaris, -lkstat is only needed on SPARC.
++if(CMAKE_HOST_SOLARIS)
++  set(UNAME "")
++  execute_process(COMMAND uname -p OUTPUT_VARIABLE UNAME)
++  if("${UNAME}" MATCHES "sparc")
++    message(INFO "Adding -lkstat to link line.")
++    set(system_libs ${system_libs} kstat)
++  endif()
++endif()
++
+ add_llvm_library(LLVMSupport
+   APFloat.cpp
+   APInt.cpp
+###
+--- tools/clang/include/clang/Basic/Makefile	2014-03-31 09:14:44.000000000 -0400
++++ tools/clang/include/clang/Basic/Makefile	2016-05-08 23:19:20.552431239 -0400
+@@ -16,8 +16,17 @@
+ 
+ INPUT_TDS = $(wildcard $(PROJ_SRC_DIR)/Diagnostic*.td)
+ 
++SVN_OR_RC :=
++
+ # Compute the Clang version from the LLVM version, unless specified explicitly.
+ ifndef CLANG_VERSION
++ifeq ($(LLVMVersion), $(findstring svn, $(LLVMVersion)), svn)
++  SVN_OR_RC := "svn"
++endif
++
++ifeq ($(LLVMVersion), $(findstring rc, $(LLVMVersion)), rc)
++  SVN_OR_RC := "rc"
++endif
+ CLANG_VERSION := $(subst svn,,$(LLVMVersion))
+ CLANG_VERSION := $(subst rc,,$(CLANG_VERSION))
+ endif
+@@ -26,6 +35,14 @@
+ CLANG_VERSION_MAJOR := $(word 1,$(CLANG_VERSION_COMPONENTS))
+ CLANG_VERSION_MINOR := $(word 2,$(CLANG_VERSION_COMPONENTS))
+ CLANG_VERSION_PATCHLEVEL := $(word 3,$(CLANG_VERSION_COMPONENTS))
++CLANG_VERSION_TAGGED_STRING :=
++
++ifeq ($(SVN_OR_RC),)
++  CLANG_VERSION_TAGGED_STRING := "\"\(tags/RELEASE_$(CLANG_VERSION_MAJOR)$(CLANG_VERSION_MINOR)$(CLANG_VERSION_PATCHLEVEL)/final\)\""
++else
++  CLANG_VERSION_TAGGED_STRING := "\"\(tags/RELEASE_$(CLANG_VERSION_MAJOR)$(CLANG_VERSION_MINOR)$(CLANG_VERSION_PATCHLEVEL)/$(SVN_OR_RC)\)\""
++endif
++
+ ifeq ($(CLANG_VERSION_PATCHLEVEL),)
+ CLANG_HAS_VERSION_PATCHLEVEL := 0
+ else
+@@ -67,4 +84,5 @@
+ 	           -e "s#@CLANG_VERSION_MINOR@#$(CLANG_VERSION_MINOR)#g" \
+ 	           -e "s#@CLANG_VERSION_PATCHLEVEL@#$(CLANG_VERSION_PATCHLEVEL)#g" \
+ 	           -e "s#@CLANG_HAS_VERSION_PATCHLEVEL@#$(CLANG_HAS_VERSION_PATCHLEVEL)#g" \
++		   -e "s#@CLANG_VERSION_TAGGED_STRING@#$(CLANG_VERSION_TAGGED_STRING:' '='')#g" \
+ 	           $< > $@
+###
+--- tools/clang/tools/libclang/Makefile	2015-07-07 21:00:30.000000000 -0400
++++ tools/clang/tools/libclang/Makefile	2016-05-08 23:19:20.577431847 -0400
+@@ -35,10 +35,16 @@
+ include $(CLANG_LEVEL)/Makefile
+ 
+ # Add soname to the library.
+-ifeq ($(HOST_OS), $(filter $(HOST_OS), Linux FreeBSD GNU GNU/kFreeBSD))
++ifeq ($(HOST_OS), $(filter $(HOST_OS), Linux FreeBSD GNU GNU/kFreeBSD SunOS))
+         LLVMLibsOptions += -Wl,-soname,lib$(LIBRARYNAME)$(SHLIBEXT)
+ endif
+ 
++# Extract everything necessary from Solaris *.a archives
++ifeq ($(HOST_OS), $(filter $(HOST_OS), SunOS))
++  SharedLinkOptions += -Wl,-z -Wl,rescan-now -Wl,-z -Wl,allextract
++  LLVMLibsOptions += -Wl,-z -Wl,defaultextract
++endif
++
+ ifeq ($(ENABLE_CLANG_ARCMT),1)
+   CXX.Flags += -DCLANG_ENABLE_ARCMT
+ endif
+###
+--- tools/llvm-shlib/Makefile	2014-08-01 02:16:03.000000000 -0400
++++ tools/llvm-shlib/Makefile	2016-05-08 23:19:20.579431896 -0400
+@@ -71,7 +71,10 @@
+ 
+ ifeq ($(HOST_OS),SunOS)
+     # add -z allextract ahead of other libraries on Solaris
+-    LLVMLibsOptions := -Wl,-z -Wl,allextract $(LLVMLibsOptions)
++    LLVMLibsOptions := -Wl,-z -Wl,rescan -Wl,-z -Wl,allextract $(LLVMLibsOptions)
++    LLVMLibsOptions += -Wl,-h -Wl,lib$(LIBRARYNAME)$(SHLIBEXT)
++    LLVMLibsOptions += -Wl,-z -Wl,defaultextract -Wl,-z -Wl,defs
++    LLVMLibsOptions += -lkstat
+ endif
+ 
+ ifeq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW))
+###
+--- tools/clang/tools/libclang/CMakeLists.txt	2015-11-11 16:46:57.000000000 -0800
++++ tools/clang/tools/libclang/CMakeLists.txt	2016-05-15 17:35:29.587888133 -0700
+@@ -92,6 +92,7 @@
+ 
+   LINK_COMPONENTS
+   ${LLVM_TARGETS_TO_BUILD}
++
+   Core
+   Support
+   )
+@@ -108,6 +109,9 @@
+ 
+     set_property(TARGET libclang APPEND_STRING PROPERTY
+                  LINK_FLAGS ${LIBCLANG_LINK_FLAGS})
++  elseif(CMAKE_HOST_SOLARIS)
++    set(LIBCLANG_LINK_FLAGS " -Wl,-z -Wl,allextract -Wl,-z -Wl,defs -Bsymbolic-functions ")
++    set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} ${LIBCLANG_LINK_FLAGS}")
+   else()
+     set_target_properties(libclang
+       PROPERTIES
+###
+--- tools/llvm-shlib/CMakeLists.txt	2015-11-04 14:11:12.000000000 -0900
++++ tools/llvm-shlib/CMakeLists.txt	2016-07-05 22:08:15.168330085 -0800
+@@ -40,12 +40,18 @@
+ 
+ add_llvm_library(LLVM SHARED DISABLE_LLVM_LINK_LLVM_DYLIB SONAME ${SOURCES})
+ 
+-list(REMOVE_DUPLICATES LIB_NAMES)
++if (LIB_NAMES)
++  list(REMOVE_DUPLICATES "LIB_NAMES")
++endif()
++
+ if("${CMAKE_SYSTEM_NAME}" STREQUAL "Linux") # FIXME: It should be "GNU ld for elf"
+   # GNU ld doesn't resolve symbols in the version script.
+   set(LIB_NAMES -Wl,--whole-archive ${LIB_NAMES} -Wl,--no-whole-archive)
+ elseif("${CMAKE_SYSTEM_NAME}" STREQUAL "Darwin")
+   set(LIB_NAMES -Wl,-all_load ${LIB_NAMES})
++elseif(CMAKE_HOST_SOLARIS)
++  set(LIB_NAMES -Wl,-z -Wl,defs -Wl,-Bsymbolic-functions -Wl,-z -Wl,allextract ${LIB_NAMES} -Wl,-z -Wl,defaultextract)
++  # message(STATUS "LIB_NAMES: ${LIB_NAMES}")
+ endif()
+ 
+ target_link_libraries(LLVM PRIVATE ${LIB_NAMES})
+###
+--- cmake/modules/HandleLLVMOptions.cmake	2016-01-06 11:05:19.000000000 -0800
++++ cmake/modules/HandleLLVMOptions.cmake	2016-05-18 19:22:28.803960478 -0700
+@@ -132,6 +132,7 @@
+ # Pass -Wl,-z,defs. This makes sure all symbols are defined. Otherwise a DSO
+ # build might work on ELF but fail on MachO/COFF.
+ if(NOT (${CMAKE_SYSTEM_NAME} MATCHES "Darwin" OR WIN32 OR CYGWIN OR
++        CMAKE_HOST_SOLARIS OR
+         ${CMAKE_SYSTEM_NAME} MATCHES "FreeBSD" OR
+         ${CMAKE_SYSTEM_NAME} MATCHES "OpenBSD") AND
+    NOT LLVM_USE_SANITIZER)
+@@ -185,13 +186,13 @@
+   endif()
+ endif()
+ 
+-if(NOT WIN32 AND NOT CYGWIN)
++if(NOT WIN32 AND NOT CYGWIN AND NOT CMAKE_HOST_SOLARIS)
+   # MinGW warns if -fvisibility-inlines-hidden is used.
+   check_cxx_compiler_flag("-fvisibility-inlines-hidden" SUPPORTS_FVISIBILITY_INLINES_HIDDEN_FLAG)
+   append_if(SUPPORTS_FVISIBILITY_INLINES_HIDDEN_FLAG "-fvisibility-inlines-hidden" CMAKE_CXX_FLAGS)
+ endif()
+ 
+-if( CMAKE_SIZEOF_VOID_P EQUAL 8 AND NOT WIN32 )
++if( CMAKE_SIZEOF_VOID_P EQUAL 8 AND NOT WIN32 AND NOT CMAKE_HOST_SOLARIS )
+   # TODO: support other platforms and toolchains.
+   if( LLVM_BUILD_32_BITS )
+     message(STATUS "Building 32 bits executables and libraries.")
+@@ -200,10 +201,12 @@
+     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 )
++endif( CMAKE_SIZEOF_VOID_P EQUAL 8 AND NOT WIN32 AND NOT CMAKE_HOST_SOLARIS )
+ 
+ if (LLVM_BUILD_STATIC)
++  if (NOT CMAKE_HOST_SOLARIS)
+   set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -static")
++  endif(CMAKE_HOST_SOLARIS)
+ endif()
+ 
+ if( XCODE )
+###
+--- lib/Transforms/Hello/CMakeLists.txt	2015-06-15 17:44:12.000000000 -0700
++++ lib/Transforms/Hello/CMakeLists.txt	2016-05-17 18:08:53.730103135 -0700
+@@ -1,14 +1,18 @@
+ # If we don't need RTTI or EH, there's no reason to export anything
+ # from the hello plugin.
+-if( NOT LLVM_REQUIRES_RTTI )
+-  if( NOT LLVM_REQUIRES_EH )
+-    set(LLVM_EXPORTED_SYMBOL_FILE ${CMAKE_CURRENT_SOURCE_DIR}/Hello.exports)
+-  endif()
+-endif()
++# It doesn't export anything anyway, regardless of RTTI or no RTTI.
++# Why does it need an empty linker mapfile?
++IF (NOT CMAKE_HOST_SOLARIS)
++  IF (NOT LLVM_REQUIRES_RTTI)
++    IF (NOT LLVM_REQUIRES_EH)
++      SET (LLVM_EXPORTED_SYMBOL_FILE ${CMAKE_CURRENT_SOURCE_DIR}/Hello.exports)
++    ENDIF()
++  ENDIF()
++ENDIF()
+ 
+-if(WIN32 OR CYGWIN)
+-  set(LLVM_LINK_COMPONENTS Core Support)
+-endif()
++if(WIN32 OR CYGWIN OR CMAKE_HOST_SOLARIS)
++  SET (LLVM_LINK_COMPONENTS Core Support)
++ENDIF()
+ 
+ add_llvm_loadable_module( LLVMHello
+   Hello.cpp
+###
+--- tools/clang/tools/driver/CMakeLists.txt	2015-11-10 04:51:25.000000000 -0800
++++ tools/clang/tools/driver/CMakeLists.txt	2016-05-21 07:44:27.981263031 -0700
+@@ -1,3 +1,7 @@
++IF(CMAKE_HOST_SOLARIS)
++  include (GNUInstallDirs)
++ENDIF(CMAKE_HOST_SOLARIS)
++
+ set( LLVM_LINK_COMPONENTS
+   ${LLVM_TARGETS_TO_BUILD}
+   Analysis
+@@ -51,9 +55,15 @@
+ 
+ add_dependencies(clang clang-headers)
+ 
++IF(CMAKE_HOST_SOLARIS)
++  install(TARGETS clang
++    RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
++    COMPONENT clang)
++ELSE()
+ install(TARGETS clang
+   RUNTIME DESTINATION bin
+   COMPONENT clang)
++ENDIF()
+ 
+ if(NOT CMAKE_CONFIGURATION_TYPES)
+   add_custom_target(install-clang
+--- tools/clang/tools/scan-view/CMakeLists.txt	2015-11-13 12:34:15.000000000 -0800
++++ tools/clang/tools/scan-view/CMakeLists.txt	2016-05-21 08:48:55.352488404 -0700
+@@ -1,3 +1,7 @@
++IF(CMAKE_HOST_SOLARIS)
++  include(GNUInstallDirs)
++ENDIF(CMAKE_HOST_SOLARIS)
++
+ option(CLANG_INSTALL_SCANVIEW "Install the scan-view tool" ON)
+ 
+ set(BinFiles
+@@ -21,7 +25,11 @@
+                          ${CMAKE_BINARY_DIR}/bin/
+                        DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/bin/${BinFile})
+     list(APPEND Depends ${CMAKE_BINARY_DIR}/bin/${BinFile})
++    IF(CMAKE_HOST_SOLARIS)
++      install(PROGRAMS bin/${BinFile} DESTINATION ${CMAKE_INSTALL_BINDIR})
++    ELSE()
+     install(PROGRAMS bin/${BinFile} DESTINATION bin)
++    ENDIF()
+   endforeach()
+ 
+   foreach(ShareFile ${ShareFiles})
+@@ -33,7 +41,12 @@
+                          ${CMAKE_BINARY_DIR}/share/scan-view/
+                        DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/share/${ShareFile})
+     list(APPEND Depends ${CMAKE_BINARY_DIR}/share/scan-view/${ShareFile})
++    IF(CMAKE_HOST_SOLARIS)
++      install(FILES share/${ShareFile} DESTINATION
++        ${CMAKE_INSTALL_DATAROOTDIR}//scan-view)
++    ELSE()
+     install(FILES share/${ShareFile} DESTINATION share/scan-view)
++    ENDIF()
+   endforeach()
+ 
+   add_custom_target(scan-view ALL DEPENDS ${Depends})
+--- tools/clang/tools/clang-check/CMakeLists.txt	2015-07-16 18:19:54.000000000 -0700
++++ tools/clang/tools/clang-check/CMakeLists.txt	2016-05-21 08:52:13.223643264 -0700
+@@ -1,3 +1,7 @@
++IF (CMAKE_HOST_SOLARIS)
++  include(GNUInstallDirs)
++ENDIF(CMAKE_HOST_SOLARIS)
++
+ set( LLVM_LINK_COMPONENTS
+   ${LLVM_TARGETS_TO_BUILD}
+   Option
+@@ -18,5 +22,9 @@
+   clangTooling
+   )
+ 
+-install(TARGETS clang-check
+-  RUNTIME DESTINATION bin)
++IF(CMAKE_HOST_SOLARIS)
++  install(TARGETS clang-check RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
++ELSE()
++  install(TARGETS clang-check RUNTIME DESTINATION bin)
++ENDIF()
++
+###
+--- tools/clang/tools/diagtool/CMakeLists.txt	2014-02-20 23:59:59.000000000 -0800
++++ tools/clang/tools/diagtool/CMakeLists.txt	2016-05-23 06:25:56.330339818 -0700
+@@ -1,6 +1,6 @@
+-set(LLVM_LINK_COMPONENTS
+-  Support
+-  )
++include(GNUInstallDirs)
++
++set(LLVM_LINK_COMPONENTS Support)
+ 
+ add_clang_executable(diagtool
+   diagtool_main.cpp
+@@ -13,11 +13,15 @@
+ 
+ target_link_libraries(diagtool
+   clangBasic
+-  clangFrontend
+-  )
++  clangFrontend)
+ 
+ if(UNIX)
+   set(CLANGXX_LINK_OR_COPY create_symlink)
+ else()
+   set(CLANGXX_LINK_OR_COPY copy)
+ endif()
++
++install(TARGETS diagtool
++        RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
++        COMPONENT diagtool)
++
+--- tools/clang/tools/c-arcmt-test/CMakeLists.txt	2014-11-05 06:04:25.000000000 -0800
++++ tools/clang/tools/c-arcmt-test/CMakeLists.txt	2016-05-23 06:30:27.431481181 -0700
+@@ -1,17 +1,16 @@
+-add_clang_executable(c-arcmt-test
+-  c-arcmt-test.c
+-  )
++include(GNUInstallDirs)
++
++add_clang_executable(c-arcmt-test c-arcmt-test.c)
+ 
+ if (LLVM_BUILD_STATIC)
+-  target_link_libraries(c-arcmt-test
+-    libclang_static
+-    )
++  target_link_libraries(c-arcmt-test libclang_static)
+ else()
+-  target_link_libraries(c-arcmt-test
+-    libclang
+-    )
++  target_link_libraries(c-arcmt-test libclang)
+ endif()
+ 
+-set_target_properties(c-arcmt-test
+-  PROPERTIES
+-  LINKER_LANGUAGE CXX)
++set_target_properties(c-arcmt-test PROPERTIES LINKER_LANGUAGE CXX)
++
++install(TARGETS c-arcmt-test
++        RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
++        COMPONENT c-arcmt-test)
++
+--- tools/clang/tools/arcmt-test/CMakeLists.txt	2014-01-31 10:09:49.000000000 -0800
++++ tools/clang/tools/arcmt-test/CMakeLists.txt	2016-05-23 06:29:00.860135211 -0700
+@@ -1,14 +1,16 @@
+-set(LLVM_LINK_COMPONENTS
+-  support
+-  )
++include(GNUInstallDirs)
+ 
+-add_clang_executable(arcmt-test
+-  arcmt-test.cpp
+-  )
++set(LLVM_LINK_COMPONENTS Support)
++
++add_clang_executable(arcmt-test arcmt-test.cpp)
+ 
+ target_link_libraries(arcmt-test
+   clangARCMigrate
+   clangBasic
+   clangFrontend
+-  clangLex
+-  )
++  clangLex)
++
++install(TARGETS arcmt-test
++        RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
++        COMPONENT arcmt-test)
++
+###
+--- tools/clang/tools/c-index-test/CMakeLists.txt	2015-11-13 14:41:14.000000000 -0800
++++ tools/clang/tools/c-index-test/CMakeLists.txt	2016-05-23 07:56:42.716288730 -0700
+@@ -1,27 +1,18 @@
+-add_clang_executable(c-index-test
+-  c-index-test.c
+-  )
++include(GNUInstallDirs)
++
++add_clang_executable(c-index-test c-index-test.c)
+ 
+ if(NOT MSVC)
+-  set_property(
+-    SOURCE c-index-test.c
+-    PROPERTY COMPILE_FLAGS "-std=gnu89"
+-    )
++  set_property( SOURCE c-index-test.c PROPERTY COMPILE_FLAGS "-std=gnu89")
+ endif()
+ 
+ if (LLVM_BUILD_STATIC)
+-  target_link_libraries(c-index-test
+-    libclang_static
+-  )
++  target_link_libraries(c-index-test libclang_static)
+ else()
+-  target_link_libraries(c-index-test
+-    libclang
+-  )
++  target_link_libraries(c-index-test libclang)
+ endif()
+ 
+-set_target_properties(c-index-test
+-  PROPERTIES
+-  LINKER_LANGUAGE CXX)
++set_target_properties(c-index-test PROPERTIES LINKER_LANGUAGE CXX)
+ 
+ # If libxml2 is available, make it available for c-index-test.
+ if (CLANG_HAVE_LIBXML)
+@@ -31,9 +22,18 @@
+ 
+ if (NOT LLVM_INSTALL_TOOLCHAIN_ONLY)
+   if(INTERNAL_INSTALL_PREFIX)
+-    set(INSTALL_DESTINATION "${INTERNAL_INSTALL_PREFIX}/bin")
++    if(CMAKE_HOST_SOLARIS)
++      set(INSTALL_DESTINATION
++          "${INTERNAL_INSTALL_PREFIX}/${CMAKE_INSTALL_BINDIR}")
++    else()
++      set(INSTALL_DESTINATION "${INTERNAL_INSTALL_PREFIX}/bin")
++    endif()
+   else()
+-    set(INSTALL_DESTINATION bin)
++    if (CMAKE_HOST_SOLARIS)
++      set(INSTALL_DESTINATION ${CMAKE_INSTALL_BINDIR})
++    else()
++      set(INSTALL_DESTINATION bin)
++    endif()
+   endif()
+ 
+   install(TARGETS c-index-test
+@@ -48,3 +48,4 @@
+               -P "${CMAKE_BINARY_DIR}/cmake_install.cmake")
+   endif()
+ endif()
++
+###
+--- tools/llvm-lto/CMakeLists.txt	2015-10-19 08:21:46.000000000 -0700
++++ tools/llvm-lto/CMakeLists.txt	2016-05-23 06:23:43.366481218 -0700
+@@ -1,3 +1,5 @@
++include(GNUInstallDirs)
++
+ set(LLVM_LINK_COMPONENTS
+   ${LLVM_TARGETS_TO_BUILD}
+   BitWriter
+@@ -6,10 +8,11 @@
+   MC
+   Object
+   Support
+-  Target
+-  )
++  Target)
++
++add_llvm_tool(llvm-lto llvm-lto.cpp)
+ 
+-add_llvm_tool(llvm-lto
+-  llvm-lto.cpp
+-  )
++install(TARGETS llvm-lto
++        RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
++        COMPONENT llvm-lto)
+ 
+###
+--- tools/clang/tools/scan-build/CMakeLists.txt	2015-11-20 10:49:02.000000000 -0800
++++ tools/clang/tools/scan-build/CMakeLists.txt	2016-05-21 09:18:25.745824278 -0700
+@@ -38,7 +38,11 @@
+                          ${CMAKE_BINARY_DIR}/bin/
+                        DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/bin/${BinFile})
+     list(APPEND Depends ${CMAKE_BINARY_DIR}/bin/${BinFile})
++    if (CMAKE_HOST_SOLARIS)
++      install(PROGRAMS bin/${BinFile} DESTINATION ${CMAKE_INSTALL_BINDIR})
++    else()
+     install(PROGRAMS bin/${BinFile} DESTINATION bin)
++    endif()
+   endforeach()
+ 
+   foreach(LibexecFile ${LibexecFiles})
+@@ -50,7 +54,12 @@
+                          ${CMAKE_BINARY_DIR}/libexec/
+                        DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/libexec/${LibexecFile})
+     list(APPEND Depends ${CMAKE_BINARY_DIR}/libexec/${LibexecFile})
++    if (CMAKE_HOST_SOLARIS)
++      install(PROGRAMS libexec/${LibexecFile} DESTINATION
++              ${CMAKE_INSTALL_LIBEXECDIR})
++    ELSE()
+     install(PROGRAMS libexec/${LibexecFile} DESTINATION libexec)
++    ENDIF()
+   endforeach()
+ 
+   foreach(ManPage ${ManPages})
+@@ -74,9 +83,15 @@
+                          ${CMAKE_BINARY_DIR}/share/scan-build/
+                        DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/share/scan-build/${ShareFile})
+     list(APPEND Depends ${CMAKE_BINARY_DIR}/share/scan-build/${ShareFile})
++    IF (CMAKE_HOST_SOLARIS)
++      install(FILES share/scan-build/${ShareFile} DESTINATION
++        ${CMAKE_INSTALL_DATAROOTDIR}/scan-build)
++    ELSE()
+     install(FILES share/scan-build/${ShareFile} DESTINATION share/scan-build)
++    ENDIF()
+   endforeach()
+ 
+   add_custom_target(scan-build ALL DEPENDS ${Depends})
+   set_target_properties(scan-build PROPERTIES FOLDER "Misc")
+ endif()
++
+--- tools/clang/tools/clang-format/CMakeLists.txt	2015-09-30 12:28:47.000000000 -0700
++++ tools/clang/tools/clang-format/CMakeLists.txt	2016-05-21 09:33:31.300900932 -0700
+@@ -1,5 +1,9 @@
+ set(LLVM_LINK_COMPONENTS support)
+ 
++if(CMAKE_HOST_SOLARIS)
++  include(GNUInstallDirs)
++endif()
++
+ add_clang_executable(clang-format
+   ClangFormat.cpp
+   )
+@@ -19,6 +23,21 @@
+   add_subdirectory(fuzzer)
+ endif()
+ 
++if(CMAKE_HOST_SOLARIS)
++  install(TARGETS clang-format RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
++  install(PROGRAMS clang-format-bbedit.applescript
++          DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/clang)
++  install(PROGRAMS clang-format-diff.py
++          DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/clang)
++  install(PROGRAMS clang-format-sublime.py
++          DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/clang)
++  install(PROGRAMS clang-format.el
++          DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/clang)
++  install(PROGRAMS clang-format.py
++          DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/clang)
++  install(PROGRAMS git-clang-format
++          DESTINATION ${CMAKE_INSTALL_BINDIR})
++else()
+ install(TARGETS clang-format RUNTIME DESTINATION bin)
+ install(PROGRAMS clang-format-bbedit.applescript DESTINATION share/clang)
+ install(PROGRAMS clang-format-diff.py DESTINATION share/clang)
+@@ -26,3 +45,5 @@
+ install(PROGRAMS clang-format.el DESTINATION share/clang)
+ install(PROGRAMS clang-format.py DESTINATION share/clang)
+ install(PROGRAMS git-clang-format DESTINATION bin)
++endif()
++
+###
+--- tools/clang/CMakeLists.txt	2016-01-05 15:51:42.000000000 -0800
++++ tools/clang/CMakeLists.txt	2016-05-23 14:00:47.358240529 -0700
+@@ -1,5 +1,7 @@
+ cmake_minimum_required(VERSION 2.8.8)
+ 
++include(GNUInstallDirs)
++
+ # FIXME: It may be removed when we use 2.8.12.
+ if(CMAKE_VERSION VERSION_LESS 2.8.12)
+   # Invalidate a couple of keywords.
+@@ -84,6 +86,7 @@
+   # They are used as destination of target generators.
+   set(LLVM_RUNTIME_OUTPUT_INTDIR ${CMAKE_BINARY_DIR}/${CMAKE_CFG_INTDIR}/bin)
+   set(LLVM_LIBRARY_OUTPUT_INTDIR ${CMAKE_BINARY_DIR}/${CMAKE_CFG_INTDIR}/lib${LLVM_LIBDIR_SUFFIX})
++
+   if(WIN32 OR CYGWIN)
+     # DLL platform -- put DLLs into bin.
+     set(LLVM_SHLIB_OUTPUT_INTDIR ${LLVM_RUNTIME_OUTPUT_INTDIR})
+@@ -196,11 +199,21 @@
+ set(DEFAULT_SYSROOT "" CACHE PATH
+   "Default <path> to all compiler invocations for --sysroot=<path>." )
+ 
++if(CMAKE_HOST_SOLARIS)
++  set(CLANG_DEFAULT_OPENMP_RUNTIME "libgomp" CACHE STRING
++      "Default OpenMP runtime used by -fopenmp.")
++else()
+ set(CLANG_DEFAULT_OPENMP_RUNTIME "libomp" CACHE STRING
+   "Default OpenMP runtime used by -fopenmp.")
++endif()
+ 
++if(CMAKE_HOST_SOLARIS)
++  set(CLANG_VENDOR "Oracle Solaris" CACHE STRING
++      "Vendor-specific text for showing with version information.")
++else()
+ set(CLANG_VENDOR "" CACHE STRING
+   "Vendor-specific text for showing with version information.")
++endif()
+ 
+ if( CLANG_VENDOR )
+   add_definitions( -DCLANG_VENDOR="${CLANG_VENDOR} " )
+@@ -399,12 +412,21 @@
+     target_link_libraries(${name} ${cmake_2_8_12_INTERFACE} ${LLVM_COMMON_LIBS})
+ 
+     if (NOT LLVM_INSTALL_TOOLCHAIN_ONLY OR ${name} STREQUAL "libclang")
++      if(CMAKE_HOST_SOLARIS)
+       install(TARGETS ${name}
+         COMPONENT ${name}
+         EXPORT ClangTargets
+-        LIBRARY DESTINATION lib${LLVM_LIBDIR_SUFFIX}
+-        ARCHIVE DESTINATION lib${LLVM_LIBDIR_SUFFIX}
++          LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
++          ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
++          RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
++      else()
++        install(TARGETS ${name}
++          COMPONENT ${name}
++          EXPORT ClangTargets
++          LIBRARY DESTINATION lib
++          ARCHIVE DESTINATION lib
+         RUNTIME DESTINATION bin)
++      endif()
+ 
+       if (${ARG_SHARED} AND NOT CMAKE_CONFIGURATION_TYPES)
+         add_custom_target(install-${name}
+@@ -443,6 +465,26 @@
+   ${CMAKE_CURRENT_SOURCE_DIR}/include
+   )
+ 
++if (CMAKE_HOST_SOLARIS)
++  if (NOT LLVM_INSTALL_TOOLCHAIN_ONLY)
++    install(DIRECTORY include/clang include/clang-c
++      DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
++      FILES_MATCHING
++      PATTERN "*.def"
++      PATTERN "*.h"
++      PATTERN "config.h" EXCLUDE
++      PATTERN ".svn" EXCLUDE
++      )
++
++    install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/include/clang
++      DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
++      FILES_MATCHING
++      PATTERN "CMakeFiles" EXCLUDE
++      PATTERN "*.inc"
++      PATTERN "*.h"
++      )
++  endif()
++else()
+ if (NOT LLVM_INSTALL_TOOLCHAIN_ONLY)
+   install(DIRECTORY include/clang include/clang-c
+     DESTINATION include
+@@ -461,12 +503,17 @@
+     PATTERN "*.h"
+     )
+ endif()
++endif()
+ 
+ if(INTERNAL_INSTALL_PREFIX)
+   set(LIBCLANG_HEADERS_INSTALL_DESTINATION "${INTERNAL_INSTALL_PREFIX}/include")
+ else()
++  if (CMAKE_HOST_SOLARIS)
++    set(LIBCLANG_HEADERS_INSTALL_DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
++  else()
+   set(LIBCLANG_HEADERS_INSTALL_DESTINATION include)
+ endif()
++endif()
+ 
+ install(DIRECTORY include/clang-c
+   COMPONENT libclang-headers
+###
+--- tools/clang/lib/Headers/CMakeLists.txt	2015-12-31 06:14:07.000000000 -0800
++++ tools/clang/lib/Headers/CMakeLists.txt	2016-05-21 09:37:34.349722741 -0700
+@@ -1,3 +1,5 @@
++include(GNUInstallDirs)
++
+ set(files
+   adxintrin.h
+   altivec.h
+@@ -101,11 +103,18 @@
+ add_custom_target(clang-headers ALL DEPENDS ${out_files})
+ set_target_properties(clang-headers PROPERTIES FOLDER "Misc")
+ 
+-install(
+-  FILES ${files} ${CMAKE_CURRENT_BINARY_DIR}/arm_neon.h
++if(CMAKE_HOST_SOLARIS)
++  install(FILES ${files} ${CMAKE_CURRENT_BINARY_DIR}/arm_neon.h
++    COMPONENT clang-headers
++    PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ WORLD_READ
++    DESTINATION
++    ${CMAKE_INSTALL_LIBDIR}/clang/${CLANG_VERSION}/include)
++else()
++  install(FILES ${files} ${CMAKE_CURRENT_BINARY_DIR}/arm_neon.h
+   COMPONENT clang-headers
+   PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ WORLD_READ
+   DESTINATION lib${LLVM_LIBDIR_SUFFIX}/clang/${CLANG_VERSION}/include)
++endif()
+ 
+ if (NOT CMAKE_CONFIGURATION_TYPES) # don't add this for IDE's.
+   add_custom_target(install-clang-headers
+@@ -114,3 +123,4 @@
+             -DCMAKE_INSTALL_COMPONENT=clang-headers
+             -P "${CMAKE_BINARY_DIR}/cmake_install.cmake")
+ endif()
++
+--- bindings/ocaml/llvm/CMakeLists.txt	2014-12-29 19:24:07.000000000 -0800
++++ bindings/ocaml/llvm/CMakeLists.txt	2016-05-21 10:59:56.318803888 -0700
+@@ -1,3 +1,7 @@
++if (CMAKE_HOST_SOLARIS)
++  include(GNUInstallDirs)
++endif()
++
+ add_ocaml_library(llvm
+   OCAML llvm
+   C     llvm_ocaml
+@@ -7,5 +11,10 @@
+   "${CMAKE_CURRENT_SOURCE_DIR}/META.llvm.in"
+   "${LLVM_LIBRARY_DIR}/ocaml/META.llvm")
+ 
++if (CMAKE_HOST_SOLARIS)
+ install(FILES "${LLVM_LIBRARY_DIR}/ocaml/META.llvm"
+-        DESTINATION lib/ocaml)
++          DESTINATION ${CMAKE_INSTALL_LIBDIR}/ocaml)
++else()
++  install(FILES "${LLVM_LIBRARY_DIR}/ocaml/META.llvm" DESTINATION lib/ocaml)
++endif()
++
+--- bindings/ocaml/backends/CMakeLists.txt	2014-12-29 19:24:07.000000000 -0800
++++ bindings/ocaml/backends/CMakeLists.txt	2016-05-21 11:02:23.891171801 -0700
+@@ -1,3 +1,7 @@
++if (CMAKE_HOST_SOLARIS)
++  include(GNUInstallDirs)
++endif()
++
+ foreach(TARGET ${LLVM_TARGETS_TO_BUILD})
+   set(OCAML_LLVM_TARGET ${TARGET})
+ 
+@@ -22,6 +26,12 @@
+     "${CMAKE_CURRENT_SOURCE_DIR}/META.llvm_backend.in"
+     "${LLVM_LIBRARY_DIR}/ocaml/META.llvm_${TARGET}")
+ 
++  if (CMAKE_HOST_SOLARIS)
++    install(FILES "${LLVM_LIBRARY_DIR}/ocaml/META.llvm_${TARGET}"
++      DESTINATION ${CMAKE_INSTALL_LIBDIR}/ocaml)
++  else()
+   install(FILES "${LLVM_LIBRARY_DIR}/ocaml/META.llvm_${TARGET}"
+           DESTINATION lib/ocaml)
++  endif()
+ endforeach()
++
+###
+--- CMakeLists.txt	2016-01-13 11:03:44.000000000 -0800
++++ CMakeLists.txt	2016-07-08 05:07:23.987736754 -0700
+@@ -2,6 +2,8 @@
+ 
+ cmake_minimum_required(VERSION 2.8.12.2)
+ 
++include(GNUInstallDirs)
++
+ if (NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
+   message(STATUS "No build type selected, default to Debug")
+   set(CMAKE_BUILD_TYPE "Debug")
+@@ -79,6 +81,16 @@
+   endif()
+ endif()
+ 
++if (${CMAKE_SYSTEM_NAME} MATCHES "SunOS")
++  if (NOT (${CMAKE_MAJOR_VERSION} GREATER 3))
++    if (NOT (${CMAKE_MINOR_VERSION} GREATER 6))
++      if (NOT ${CMAKE_HOST_SOLARIS} EQUAL 1)
++        message(ERROR "You must provide -DCMAKE_HOST_SOLARIS:BOOL=TRUE for CMake < 3.6.0")
++      endif()
++    endif()
++  endif()
++endif()
++
+ # Add path for custom modules
+ set(CMAKE_MODULE_PATH
+   ${CMAKE_MODULE_PATH}
+@@ -334,6 +346,12 @@
+ # Define the default arguments to use with 'lit', and an option for the user to
+ # override.
+ set(LIT_ARGS_DEFAULT "-sv")
++if (CMAKE_HOST_SOLARIS)
++  set(LIT_ARGS_DEFAULT "${LIT_ARGS_DEFAULT} --threads=1")
++  set(LIT_ARGS_DEFAULT "${LIT_ARGS_DEFAULT} --succinct")
++  set(LIT_ARGS_DEFAULT "${LIT_ARGS_DEFAULT} --no-progress-bar")
++endif()
++
+ if (MSVC_IDE OR XCODE)
+   set(LIT_ARGS_DEFAULT "${LIT_ARGS_DEFAULT} --no-progress-bar")
+ endif()
+@@ -554,20 +572,33 @@
+   ${LLVM_INCLUDE_DIR}/llvm/Support/DataTypes.h)
+ 
+ # They are not referenced. See set_output_directory().
++if(CMAKE_HOST_SOLARIS)
++  set(CMAKE_RUNTIME_OUTPUT_DIRECTORY
++      ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_BINIR})
++  set(CMAKE_LIBRARY_OUTPUT_DIRECTORY
++      ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR})
++  set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY
++      ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR})
++else()
+ set( CMAKE_RUNTIME_OUTPUT_DIRECTORY ${LLVM_BINARY_DIR}/bin )
+ set( CMAKE_LIBRARY_OUTPUT_DIRECTORY ${LLVM_BINARY_DIR}/lib${LLVM_LIBDIR_SUFFIX} )
+ set( CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${LLVM_BINARY_DIR}/lib${LLVM_LIBDIR_SUFFIX} )
++endif()
+ 
+ set(CMAKE_BUILD_WITH_INSTALL_RPATH ON)
++
+ if (APPLE)
+   set(CMAKE_INSTALL_NAME_DIR "@rpath")
+   set(CMAKE_INSTALL_RPATH "@executable_path/../lib")
+ else(UNIX)
+   if(NOT DEFINED CMAKE_INSTALL_RPATH)
++    if (NOT CMAKE_HOST_SOLARIS)
+     set(CMAKE_INSTALL_RPATH "\$ORIGIN/../lib${LLVM_LIBDIR_SUFFIX}")
+     if(${CMAKE_SYSTEM_NAME} MATCHES "(FreeBSD|DragonFly)")
+       set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-z,origin")
+-      set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,-z,origin")
++        set(CMAKE_SHARED_LINKER_FLAGS
++          "${CMAKE_SHARED_LINKER_FLAGS} -Wl,-z,origin")
++      endif()
+     endif()
+   endif(NOT DEFINED CMAKE_INSTALL_RPATH)
+ endif()
+@@ -639,6 +670,12 @@
+   llvm_replace_compiler_option(CMAKE_CXX_FLAGS_RELEASE "-O3" "-O2")
+ endif()
+ 
++if(CMAKE_HOST_SOLARIS)
++  llvm_replace_compiler_option(CMAKE_C_FLAGS_RELEASE "-O3" "-O0")
++  llvm_replace_compiler_option(CMAKE_CXX_FLAGS_RELEASE "-O3" "-O0")
++  llvm_replace_compiler_option(CMAKE_ASM_FLAGS_RELEASE "-O3" "-O0")
++endif()
++
+ # Put this before tblgen. Else we have a circular dependence.
+ add_subdirectory(lib/Support)
+ add_subdirectory(lib/TableGen)
+###
+--- cmake/modules/AddLLVM.cmake	2016-02-12 09:52:29.000000000 -0800
++++ cmake/modules/AddLLVM.cmake	2016-05-21 11:50:17.129351767 -0700
+@@ -2,6 +2,17 @@
+ include(LLVM-Config)
+ include(DetermineGCCCompatible)
+ 
++if (CMAKE_HOST_SOLARIS)
++  include(GNUInstallDirs)
++endif()
++
++if (CMAKE_HOST_SOLARIS)
++  SET (LLVM_REQUIRES_EH ON)
++  SET (LLVM_ENABLE_EH ON)
++  SET (LLVM_REQUIRES_RTTI ON)
++  SET (LLVM_ENABLE_RTTI ON)
++endif(CMAKE_HOST_SOLARIS)
++
+ function(llvm_update_compile_flags name)
+   get_property(sources TARGET ${name} PROPERTY SOURCES)
+   if("${sources}" MATCHES "\\.c(;|$)")
+@@ -69,7 +80,26 @@
+       COMMENT "Creating export file for ${target_name}")
+     set_property(TARGET ${target_name} APPEND_STRING PROPERTY
+                  LINK_FLAGS " -Wl,-exported_symbols_list,${CMAKE_CURRENT_BINARY_DIR}/${native_export_file}")
+-  elseif(LLVM_HAVE_LINK_VERSION_SCRIPT)
++  elseif(CMAKE_HOST_SOLARIS)
++    # Gold and BFD ld require a version script rather than a plain list.
++    set(native_export_file "${target_name}.exports")
++    add_custom_command(OUTPUT ${native_export_file}
++      COMMAND /usr/gnu/bin/echo "$mapfile_version 2" > ${native_export_file}
++      COMMAND /usr/gnu/bin/echo "" >> ${native_export_file}
++      COMMAND /usr/gnu/bin/echo "SYMBOL_SCOPE {" >> ${native_export_file}
++      COMMAND /usr/gnu/bin/grep -q "[[:alnum:]]" ${export_file} && /usr/gnu/bin/echo "  global:" >> ${native_export_file} || :
++      COMMAND /usr/gnu/bin/sed -e "s/$/;/" -e "s/^/    /" < ${export_file} >> ${native_export_file}
++      # COMMAND echo "  local: *;" >> ${native_export_file}
++      COMMAND /usr/gnu/bin/echo "};" >> ${native_export_file}
++      COMMAND /usr/gnu/bin/touch -am ${CMAKE_CURRENT_BINARY_DIR}/${native_export_file}
++      DEPENDS ${export_file}
++      VERBATIM
++      COMMENT "Creating export file for ${target_name}")
++      set_property(TARGET ${target_name} APPEND_STRING PROPERTY
++                   LINK_FLAGS "  -Wl,-M,${CMAKE_CURRENT_BINARY_DIR}/${native_export_file}")
++    set_property(TARGET ${target_name} APPEND_STRING PROPERTY
++      LINK_FLAGS "  -Wl,-M,${CMAKE_CURRENT_BINARY_DIR}/${native_export_file}")
++  elseif(LLVM_HAVE_LINK_VERSION_SCRIPT AND NOT CMAKE_HOST_SOLARIS)
+     # Gold and BFD ld require a version script rather than a plain list.
+     set(native_export_file "${target_name}.exports")
+     # FIXME: Don't write the "local:" line on OpenBSD.
+@@ -82,13 +112,8 @@
+       DEPENDS ${export_file}
+       VERBATIM
+       COMMENT "Creating export file for ${target_name}")
+-    if (${CMAKE_SYSTEM_NAME} MATCHES "SunOS")
+-      set_property(TARGET ${target_name} APPEND_STRING PROPERTY
+-                   LINK_FLAGS "  -Wl,-M,${CMAKE_CURRENT_BINARY_DIR}/${native_export_file}")
+-    else()
+       set_property(TARGET ${target_name} APPEND_STRING PROPERTY
+                    LINK_FLAGS "  -Wl,--version-script,${CMAKE_CURRENT_BINARY_DIR}/${native_export_file}")
+-    endif()
+   else()
+     set(native_export_file "${target_name}.def")
+ 
+@@ -529,11 +554,13 @@
+     ""
+     ""
+     ${ARGN})
++
+   if( BUILD_SHARED_LIBS )
+     llvm_add_library(${name} SHARED ${ARGN})
+   else()
+     llvm_add_library(${name} ${ARGN})
+   endif()
++
+   # The gtest libraries should not be installed or exported as a target
+   if ("${name}" STREQUAL gtest OR "${name}" STREQUAL gtest_main)
+     set(_is_gtest TRUE)
+@@ -546,16 +573,37 @@
+     set_target_properties( ${name} PROPERTIES EXCLUDE_FROM_ALL ON)
+   elseif(NOT _is_gtest)
+     if (NOT LLVM_INSTALL_TOOLCHAIN_ONLY OR ${name} STREQUAL "LTO")
+-      set(install_dir lib${LLVM_LIBDIR_SUFFIX})
++      if (CMAKE_HOST_SOLARIS)
++        set(install_dir ${CMAKE_INSTALL_LIBDIR})
++      else()
++        set(install_dir lib)
++      endif()
++
+       if(ARG_SHARED OR BUILD_SHARED_LIBS)
+         if(WIN32 OR CYGWIN OR MINGW)
+           set(install_type RUNTIME)
+           set(install_dir bin)
+         else()
+           set(install_type LIBRARY)
++          if (CMAKE_HOST_SOLARIS)
++            set(install_dir ${CMAKE_INSTALL_LIBDIR})
+         endif()
++        endif()
++      elseif(LLVM_BUILD_LVLM_DYLIB)
++        if (CMAKE_HOST_SOLARIS)
++          set(install_type RUNTIME)
++          set(install_dir ${CMAKE_INSTALL_BINDIR})
++        else()
++          set(install_type RUNTIME)
++          set(install_dir bin)
++        endif()
+       else()
+         set(install_type ARCHIVE)
++        if (CMAKE_HOST_SOLARIS)
++          set(install_dir ${CMAKE_INSTALL_LIBDIR})
++        else()
++          set(install_dir lib)
++        endif()
+       endif()
+ 
+       install(TARGETS ${name}
+@@ -590,13 +638,26 @@
+           # DLL platform
+           set(dlldir "bin")
+         else()
++          if (CMAKE_HOST_SOLARIS)
++            set(dlldir ${CMAKE_INSTALL_LIBDIR})
++          else()
+           set(dlldir "lib${LLVM_LIBDIR_SUFFIX}")
+         endif()
++        endif()
++
++        if (CMAKE_HOST_SOLARIS)
++          install(TARGETS ${name}
++            EXPORT LLVMExports
++            LIBRARY DESTINATION ${dlldir}
++            ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR})
++        else()
+         install(TARGETS ${name}
+           EXPORT LLVMExports
+           LIBRARY DESTINATION ${dlldir}
+           ARCHIVE DESTINATION lib${LLVM_LIBDIR_SUFFIX})
+       endif()
++      endif()
++
+       set_property(GLOBAL APPEND PROPERTY LLVM_EXPORTS ${name})
+     endif()
+   endif()
+@@ -700,10 +761,17 @@
+   list(FIND LLVM_TOOLCHAIN_TOOLS ${name} LLVM_IS_${name}_TOOLCHAIN_TOOL)
+   if (LLVM_IS_${name}_TOOLCHAIN_TOOL GREATER -1 OR NOT LLVM_INSTALL_TOOLCHAIN_ONLY)
+     if( LLVM_BUILD_TOOLS )
++      if (CMAKE_HOST_SOLARIS)
+       install(TARGETS ${name}
+               EXPORT LLVMExports
+-              RUNTIME DESTINATION bin
++          RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
++              COMPONENT ${name})
++      else()
++        install(TARGETS ${name}
++          EXPORT LLVMExports
++          RUNTIME DESTINATION bin/${LLVM_BINDIR_SUFFIX}
+               COMPONENT ${name})
++      endif()
+ 
+       if (NOT CMAKE_CONFIGURATION_TYPES)
+         add_custom_target(install-${name}
+@@ -737,9 +805,16 @@
+   add_llvm_executable(${name} DISABLE_LLVM_LINK_LLVM_DYLIB ${ARGN})
+   set_target_properties(${name} PROPERTIES FOLDER "Utils")
+   if( LLVM_INSTALL_UTILS )
++    if (CMAKE_HOST_SOLARIS)
++    install (TARGETS ${name}
++        RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
++      COMPONENT ${name})
++    else()
+     install (TARGETS ${name}
+       RUNTIME DESTINATION bin
+       COMPONENT ${name})
++    endif()
++
+     if (NOT CMAKE_CONFIGURATION_TYPES)
+       add_custom_target(install-${name}
+                         DEPENDS ${name}
+###
+--- cmake/modules/TableGen.cmake	2015-10-23 12:48:17.000000000 -0700
++++ cmake/modules/TableGen.cmake	2016-05-21 10:57:12.766140197 -0700
+@@ -2,6 +2,10 @@
+ # Extra parameters for `tblgen' may come after `ofn' parameter.
+ # Adds the name of the generated file to TABLEGEN_OUTPUT.
+ 
++if (CMAKE_HOST_SOLARIS)
++  include(GNUInstallDirs)
++endif()
++
+ function(tablegen project ofn)
+   # Validate calling context.
+   foreach(v
+@@ -138,10 +142,18 @@
+       set_target_properties(${target} PROPERTIES LINK_FLAGS -Wl,--stack,16777216)
+     endif(CMAKE_SIZEOF_VOID_P MATCHES "8")
+   endif( MINGW )
++
+   if (${project} STREQUAL LLVM AND NOT LLVM_INSTALL_TOOLCHAIN_ONLY)
++    if (CMAKE_HOST_SOLARIS)
++      install(TARGETS ${target}
++        EXPORT LLVMExports
++        RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
++    else()
+     install(TARGETS ${target}
+             EXPORT LLVMExports
+             RUNTIME DESTINATION bin)
+   endif()
++  endif()
+   set_property(GLOBAL APPEND PROPERTY LLVM_EXPORTS ${target})
+ endmacro()
++
+###
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/032-solaris-LLVM-libTarget-SPARC.patch	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,308 @@
+# 22777179 implement -mtune= | -march= | -mcpu= in clang SPARC
+# 22778085 LLVM is using %icc when it should be using %xcc
+# 22778089 the SPARCV9 IS implementation is incomplete
+# 22778098 LLVM should emit proc identifiers in SPARC assembler (capabilities)
+# 3.9.X for upstream.
+--- lib/Target/Sparc/Sparc.td	2015-03-27 20:03:51.000000000 -0800
++++ lib/Target/Sparc/Sparc.td	2016-06-30 08:30:11.896274715 -0800
+@@ -35,13 +35,15 @@
+ def FeatureVIS3
+   : SubtargetFeature<"vis3", "IsVIS3", "true",
+                      "Enable Visual Instruction Set extensions III">;
+-
+ def FeatureHardQuad
+   : SubtargetFeature<"hard-quad-float", "HasHardQuad", "true",
+                      "Enable quad-word floating point instructions">;
+-
+-def UsePopc : SubtargetFeature<"popc", "UsePopc", "true",
+-                               "Use the popc (population count) instruction">;
++def UsePopc
++  : SubtargetFeature<"popc", "UsePopc", "true",
++                     "Use the popc (population count) instruction">;
++def UseHWCap
++  : SubtargetFeature<"hwcap", "UseHWCap", "true",
++                      "Use SPARC Hardware Capabiliies">;
+ 
+ //===----------------------------------------------------------------------===//
+ // Register File, Calling Conv, Instruction Descriptions
+@@ -74,10 +76,46 @@
+ def : Proc<"sparclite86x",    []>;
+ def : Proc<"sparclet",        []>;
+ def : Proc<"tsc701",          []>;
+-def : Proc<"v9",              [FeatureV9]>;
+-def : Proc<"ultrasparc",      [FeatureV9, FeatureV8Deprecated, FeatureVIS]>;
++def : Proc<"generic32",       [FeatureV9, FeatureV8Deprecated,
++                               FeatureVIS, FeatureVIS2]>;
++def : Proc<"generic64",       [FeatureV9, FeatureV8Deprecated,
++                               FeatureVIS, FeatureVIS2]>;
++def : Proc<"v8plus",          [FeatureV9, FeatureVIS]>;
++def : Proc<"v8plusa",         [FeatureV9, FeatureVIS, FeatureV8Deprecated,
++                               FeatureVIS2]>;
++def : Proc<"v8plusb",         [FeatureV9, FeatureV8Deprecated,
++                               FeatureVIS, FeatureVIS2, FeatureVIS3]>;
++def : Proc<"v8plusc",         [FeatureV9, FeatureV8Deprecated, FeatureVIS,
++                               FeatureVIS2, FeatureVIS3]>;
++def : Proc<"v8plusd",         [FeatureV9, FeatureV8Deprecated, FeatureVIS,
++                               FeatureVIS2, FeatureVIS3]>;
++def : Proc<"v8pluse",         [FeatureV9, FeatureV8Deprecated, UsePopc,
++                               FeatureVIS, FeatureVIS2, FeatureVIS3]>;
++def : Proc<"v8plusm",         [FeatureV9, FeatureV8Deprecated, UsePopc,
++                               FeatureVIS, FeatureVIS2, FeatureVIS3]>;
++def : Proc<"v8plusv",         [FeatureV9, FeatureV8Deprecated, UsePopc,
++                               FeatureVIS, FeatureVIS2, FeatureVIS3]>;
++def : Proc<"v9",              [FeatureV9, FeatureV8Deprecated, FeatureVIS]>;
++def : Proc<"v9a",             [FeatureV9, FeatureV8Deprecated,
++                               FeatureVIS, FeatureVIS2]>;
++def : Proc<"v9b",             [FeatureV9, FeatureVIS, FeatureV8Deprecated,
++                               FeatureVIS2, FeatureVIS3]>;
++def : Proc<"v9c",             [FeatureV9, FeatureV8Deprecated,
++                               FeatureVIS, FeatureVIS2, FeatureVIS3]>;
++def : Proc<"v9d",             [FeatureV9, FeatureV8Deprecated,
++                               FeatureVIS, FeatureVIS2, FeatureVIS3]>;
++def : Proc<"v9e",             [FeatureV9, FeatureV8Deprecated, UsePopc,
++                               FeatureVIS, FeatureVIS2, FeatureVIS3]>;
++def : Proc<"v9m",             [FeatureV9, FeatureV8Deprecated, UsePopc,
++                               FeatureVIS, FeatureVIS2, FeatureVIS3]>;
++def : Proc<"v9v",             [FeatureV9, FeatureV8Deprecated, UsePopc,
++                               FeatureVIS, FeatureVIS2, FeatureVIS3]>;
++def : Proc<"ultrasparc",      [FeatureV9, FeatureVIS]>;
++def : Proc<"ultrasparc2",     [FeatureV9, FeatureV8Deprecated, FeatureVIS]>;
+ def : Proc<"ultrasparc3",     [FeatureV9, FeatureV8Deprecated, FeatureVIS,
+                                FeatureVIS2]>;
++def : Proc<"ultrasparc4",     [FeatureV9, FeatureV8Deprecated, FeatureVIS,
++                               FeatureVIS2, FeatureVIS3]>;
+ def : Proc<"niagara",         [FeatureV9, FeatureV8Deprecated, FeatureVIS,
+                                FeatureVIS2]>;
+ def : Proc<"niagara2",        [FeatureV9, FeatureV8Deprecated, UsePopc,
+@@ -86,7 +124,10 @@
+                                FeatureVIS, FeatureVIS2]>;
+ def : Proc<"niagara4",        [FeatureV9, FeatureV8Deprecated, UsePopc,
+                                FeatureVIS, FeatureVIS2, FeatureVIS3]>;
+-
++def : Proc<"sparc4",          [FeatureV9, FeatureV8Deprecated, UsePopc,
++                               FeatureVIS, FeatureVIS2, FeatureVIS3]>;
++def : Proc<"sparc5",          [FeatureV9, FeatureV8Deprecated, UsePopc,
++                               FeatureVIS, FeatureVIS2, FeatureVIS3]>;
+ 
+ //===----------------------------------------------------------------------===//
+ // Declare the target which we are implementing
+###
+--- lib/Target/Sparc/SparcRegisterInfo.td	2015-10-04 01:11:22.000000000 -0800
++++ lib/Target/Sparc/SparcRegisterInfo.td	2016-06-29 17:37:09.214126550 -0800
+@@ -56,7 +56,9 @@
+ }
+ 
+ // Control Registers
+-def ICC : SparcCtrlReg<0, "ICC">; // This represents icc and xcc in 64-bit code.
++def ICC : SparcCtrlReg<0, "ICC">; // This represents icc in 32-bit code.
++def XCC : SparcCtrlReg<0, "XCC">; // This represents xcc in 64-bit code.
++
+ foreach I = 0-3 in
+   def FCC#I : SparcCtrlReg<I, "FCC"#I>;
+ 
+@@ -64,6 +66,7 @@
+ 
+ // Y register
+ def Y : SparcCtrlReg<0, "Y">, DwarfRegNum<[64]>;
++
+ // Ancillary state registers (implementation defined)
+ def ASR1 : SparcCtrlReg<1, "ASR1">;
+ def ASR2 : SparcCtrlReg<2, "ASR2">;
+###
+--- lib/Target/Sparc/SparcInstrInfo.td	2015-12-11 10:20:16.000000000 -0900
++++ lib/Target/Sparc/SparcInstrInfo.td	2016-07-02 19:46:36.045655245 -0800
+@@ -348,7 +348,7 @@
+ }
+ 
+ // GETPCX for PIC
+-let Defs = [O7] in {
++let Defs = [O7], hasSideEffects = 1 in {
+   def GETPCX : Pseudo<(outs getPCX:$getpcseq), (ins), "$getpcseq", [] >;
+ }
+ 
+###
+--- lib/Target/Sparc/SparcSubtarget.cpp	2015-09-15 08:17:27.000000000 -0800
++++ lib/Target/Sparc/SparcSubtarget.cpp	2016-06-30 08:32:19.524226970 -0800
+@@ -33,11 +33,12 @@
+   IsVIS = false;
+   HasHardQuad = false;
+   UsePopc = false;
++  UseHWCap = false;
+ 
+   // Determine default and user specified characteristics
+   std::string CPUName = CPU;
+   if (CPUName.empty())
+-    CPUName = (Is64Bit) ? "v9" : "v8";
++    CPUName = (Is64Bit) ? "v9a" : "v8plusa";
+ 
+   // Parse features string.
+   ParseSubtargetFeatures(CPUName, FS);
+###
+--- lib/Target/Sparc/SparcSubtarget.h	2015-09-10 13:49:06.000000000 -0800
++++ lib/Target/Sparc/SparcSubtarget.h	2016-06-30 08:31:39.266062160 -0800
+@@ -37,6 +37,7 @@
+   bool Is64Bit;
+   bool HasHardQuad;
+   bool UsePopc;
++  bool UseHWCap;
+   SparcInstrInfo InstrInfo;
+   SparcTargetLowering TLInfo;
+   TargetSelectionDAGInfo TSInfo;
+@@ -69,6 +70,7 @@
+   bool useDeprecatedV8Instructions() const { return V8DeprecatedInsts; }
+   bool hasHardQuad() const { return HasHardQuad; }
+   bool usePopc() const { return UsePopc; }
++  bool useHWCap() const { return UseHWCap; }
+ 
+   /// ParseSubtargetFeatures - Parses features string setting specified
+   /// subtarget options.  Definition of function is auto generated by tblgen.
+###
+--- lib/Target/Sparc/SparcISelLowering.cpp	2015-12-15 14:07:16.000000000 -0900
++++ lib/Target/Sparc/SparcISelLowering.cpp	2016-07-02 17:42:55.774845330 -0800
+@@ -3202,10 +3202,15 @@
+ SparcTargetLowering::getConstraintType(StringRef Constraint) const {
+   if (Constraint.size() == 1) {
+     switch (Constraint[0]) {
+-    default:  break;
+-    case 'r': return C_RegisterClass;
++    default:
++      break;
++    case 'f':
++    case 'r':
++      return C_RegisterClass;
++      break;
+     case 'I': // SIMM13
+       return C_Other;
++      break;
+     }
+   }
+ 
+@@ -3277,11 +3282,22 @@
+                                                   MVT VT) const {
+   if (Constraint.size() == 1) {
+     switch (Constraint[0]) {
++    case 'f':
++      if (VT == MVT::f32)
++        return std::make_pair(0U, &SP::FPRegsRegClass);
++      else if (VT == MVT::f64)
++        return std::make_pair(0U, &SP::DFPRegsRegClass);
++      else if (VT == MVT::f128)
++        return std::make_pair(0U, &SP::QFPRegsRegClass);
++      else
++        llvm_unreachable("Invalid floating-point MachineValueType!");
++      break;
+     case 'r':
+       if (VT == MVT::v2i32)
+         return std::make_pair(0U, &SP::IntPairRegClass);
+       else
+         return std::make_pair(0U, &SP::IntRegsRegClass);
++      break;
+     }
+   } else if (!Constraint.empty() && Constraint.size() <= 5
+               && Constraint[0] == '{' && *(Constraint.end()-1) == '}') {
+###
+--- lib/Target/Sparc/InstPrinter/SparcInstPrinter.cpp	2015-06-08 16:31:39.000000000 -0800
++++ lib/Target/Sparc/InstPrinter/SparcInstPrinter.cpp	2016-07-03 18:29:49.019851395 -0800
+@@ -17,9 +17,13 @@
+ #include "llvm/MC/MCInst.h"
+ #include "llvm/MC/MCRegisterInfo.h"
+ #include "llvm/MC/MCSymbol.h"
++#include "llvm/Target/TargetRegisterInfo.h"
+ #include "llvm/Support/raw_ostream.h"
+ using namespace llvm;
+ 
++#include <algorithm>
++#include <cctype>
++
+ #define DEBUG_TYPE "asm-printer"
+ 
+ // The generated AsmMatcher SparcGenAsmWriter uses "Sparc" as the target
+@@ -170,9 +174,29 @@
+   O << SPARCCondCodeToString((SPCC::CondCodes)CC);
+ }
+ 
+-bool SparcInstPrinter::printGetPCX(const MCInst *MI, unsigned opNum,
++bool SparcInstPrinter::printGetPCX(const MCInst *MI, unsigned OpNo,
+                                    const MCSubtargetInfo &STI,
+                                    raw_ostream &O) {
+-  llvm_unreachable("FIXME: Implement SparcInstPrinter::printGetPCX.");
++  const MCOperand &MO = MI->getOperand(OpNo);
++  assert(MO.isReg() && "MCOperand is not a register!");
++
++  unsigned RegNum = MO.getReg();
++  assert(TargetRegisterInfo::isPhysicalRegister(RegNum) &&
++         "MCOperand is not a physical register!");
++  assert(RegNum != SP::O7 &&
++         "Cannot assign %o7 as destination for GetPCX!");
++
++  std::string Operand = "%";
++  Operand += getRegisterName(RegNum);
++  std::transform(Operand.begin(), Operand.end(), Operand.begin(), tolower);
++
++  O << "\n\tsethi   %hi(_GLOBAL_OFFSET_TABLE_-8), "
++    << Operand.c_str() << "\n";
++  O << "\tadd   " << Operand.c_str() << ", %lo(_GLOBAL_OFFSET_TABLE_-4), "
++    << Operand.c_str() << "\n";
++  O << "\tadd   " << Operand.c_str() << ", %o7, " << Operand.c_str() << "\n";
++  O << "\tnop\n";
++
+   return true;
+ }
++
+###
+--- lib/Target/Sparc/SparcAsmPrinter.cpp	2015-10-19 16:59:43.000000000 -0800
++++ lib/Target/Sparc/SparcAsmPrinter.cpp	2016-07-03 18:07:26.477720690 -0800
+@@ -173,17 +173,16 @@
+ }
+ 
+ void SparcAsmPrinter::LowerGETPCXAndEmitMCInsts(const MachineInstr *MI,
+-                                                const MCSubtargetInfo &STI)
+-{
+-  MCSymbol *GOTLabel   =
++                                                const MCSubtargetInfo &STI) {
++  MCSymbol *GOTLabel =
+     OutContext.getOrCreateSymbol(Twine("_GLOBAL_OFFSET_TABLE_"));
+ 
+   const MachineOperand &MO = MI->getOperand(0);
+-  assert(MO.getReg() != SP::O7 &&
+-         "%o7 is assigned as destination for getpcx!");
+-
+-  MCOperand MCRegOP = MCOperand::createReg(MO.getReg());
++  unsigned RegNum = MO.getReg();
++  assert((RegNum != SP::O7 && RegNum != SP::L7) &&
++         "%o7 | %l7 are assigned as destination for getpcx!");
+ 
++  MCOperand MCRegOP = MCOperand::createReg(RegNum);
+ 
+   if (TM.getRelocationModel() != Reloc::PIC_) {
+     // Just load the address of GOT to MCRegOP.
+@@ -214,6 +213,7 @@
+       MCOperand imm = MCOperand::createExpr(MCConstantExpr::create(32,
+                                                                    OutContext));
+       EmitSHL(*OutStreamer, MCRegOP, imm, MCRegOP, STI);
++
+       // Use register %o7 to load the lower 32 bits.
+       MCOperand RegO7 = MCOperand::createReg(SP::O7);
+       EmitHiLo(*OutStreamer, GOTLabel,
+@@ -225,6 +225,12 @@
+     return;
+   }
+ 
++#if 0
++  MCInst MCI;
++  LowerSparcMachineInstrToMCInst(MI, MCI, *this);
++  const MCInstrDesc &MCID = MI->getDesc();
++#endif
++
+   MCSymbol *StartLabel = OutContext.createTempSymbol();
+   MCSymbol *EndLabel   = OutContext.createTempSymbol();
+   MCSymbol *SethiLabel = OutContext.createTempSymbol();
+@@ -417,6 +423,7 @@
+     default:
+       // See if this is a generic print operand
+       return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
++    case 'f':
+     case 'r':
+      break;
+     }
+###
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/033-solaris-LLVM-JIT.patch	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,1636 @@
+# 23593143 lli JIT bitcode parsing creates a main function with wrong argc/argv
+# 22804878 - implement LLVM JIT on Solaris SPARC
+# 22804891 - implement LLVM JIT on Solaris Intel
+# 3.9.X for upstream.
+--- include/llvm/Support/ELFRelocs/Sparc.def	2015-06-18 07:05:15.000000000 -0800
++++ include/llvm/Support/ELFRelocs/Sparc.def	2016-06-11 11:39:24.768074060 -0800
+@@ -87,3 +87,8 @@
+ ELF_RELOC(R_SPARC_GOTDATA_OP_HIX22,  82)
+ ELF_RELOC(R_SPARC_GOTDATA_OP_LOX10,  83)
+ ELF_RELOC(R_SPARC_GOTDATA_OP,     84)
++ELF_RELOC(R_SPARC_H34,            85)
++ELF_RELOC(R_SPARC_SIZE32,         86)
++ELF_RELOC(R_SPARC_SIZE64,         87)
++ELF_RELOC(R_SPARC_WDISP10,        88)
++ELF_RELOC(R_SPARC_NUM,            89)
+--- lib/ExecutionEngine/RuntimeDyld/RuntimeDyldImpl.h	2016-01-10 09:51:50.000000000 -0900
++++ lib/ExecutionEngine/RuntimeDyld/RuntimeDyldImpl.h	2016-06-11 21:03:29.000000000 -0800
+@@ -117,6 +117,11 @@
+     assert(StubOffset <= AllocationSize && "Not enough space allocated!");
+   }
+ 
++  void setStubOffset(unsigned Value) {
++    StubOffset = Value;
++    assert(StubOffset <= AllocationSize && "Not enough space allocated!");
++  }
++
+   uintptr_t getObjAddress() const { return ObjAddress; }
+ };
+ 
+###
+--- lib/ExecutionEngine/RuntimeDyld/RuntimeDyldELF.h	2015-11-23 12:47:51.000000000 -0900
++++ lib/ExecutionEngine/RuntimeDyld/RuntimeDyldELF.h	2016-06-23 07:17:02.829718055 -0800
+@@ -49,6 +49,14 @@
+   void resolvePPC64Relocation(const SectionEntry &Section, uint64_t Offset,
+                               uint64_t Value, uint32_t Type, int64_t Addend);
+ 
++  void resolveSPARC3264Relocation(const SectionEntry &Section,
++                                  uint64_t Offset, uint64_t Value,
++                                  uint32_t Type, int32_t Addend);
++
++  void resolveSPARC64Relocation(const SectionEntry &Section,
++                                uint64_t Offset, uint64_t Value,
++                                uint32_t Type, int64_t Addend);
++
+   void resolveSystemZRelocation(const SectionEntry &Section, uint64_t Offset,
+                                 uint64_t Value, uint32_t Type, int64_t Addend);
+ 
+@@ -73,6 +81,10 @@
+       return 16;
+     else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le)
+       return 44;
++    else if (Arch == Triple::sparc)
++      return 16;
++    else if (Arch == Triple::sparcv9)
++      return 32;
+     else if (Arch == Triple::x86_64)
+       return 6; // 2-byte jmp instruction + 32-bit relative address
+     else if (Arch == Triple::systemz)
+###
+--- lib/ExecutionEngine/RuntimeDyld/RuntimeDyldELF.cpp	2015-11-24 11:37:01.000000000 -0900
++++ lib/ExecutionEngine/RuntimeDyld/RuntimeDyldELF.cpp	2016-07-04 10:45:23.637041765 -0800
+@@ -1016,6 +1016,448 @@
+   }
+ }
+ 
++/// SPARC ELF Relocations - common to 32-bit and 64-bit.
++/// https://docs.oracle.com/cd/E19683-01/817-3677/chapter6-24/index.html
++void RuntimeDyldELF::resolveSPARC3264Relocation(const SectionEntry &Section,
++                                                uint64_t Offset,
++                                                uint64_t Value,
++                                                uint32_t Type,
++                                                int32_t Addend) {
++  uint64_t *TargetAddress =
++    reinterpret_cast<uint64_t*>(reinterpret_cast<void*>(Section.getAddress()));
++  uint64_t *TargetPtr =
++    reinterpret_cast<uint64_t*>(Section.getAddressWithOffset(Offset));
++  uint32_t Reloc = 0U;
++  uint8_t *TargetPtr8 = nullptr;
++  uint16_t *TargetPtr16 = nullptr;
++  uint32_t *TargetPtr32 = nullptr;
++  uint32_t LoadAddress = Section.getLoadAddressWithOffset(Offset) & 0xFFFFFFFF;
++  uint32_t TargetValue = 0U;
++  int32_t RS = 0;
++  int32_t RM = 0;
++
++  switch (Type) {
++  default:
++    llvm_unreachable("Unimplemented SPARC32 Relocation Type!");
++    break;
++  case ELF::R_SPARC_NONE:
++    break;
++  case ELF::R_SPARC_SIZE32:
++    *TargetPtr = Section.getSize() + Addend;
++    break;
++  case ELF::R_SPARC_RELATIVE:
++    *TargetPtr = LoadAddress + Addend;
++    break;
++  case ELF::R_SPARC_COPY:
++    Value += Addend;
++    (void) std::memcpy(TargetPtr,
++                       reinterpret_cast<void*>(static_cast<uintptr_t>(Value)),
++                       Section.getSize());
++    break;
++  case ELF::R_SPARC_8:
++    TargetPtr8 = reinterpret_cast<uint8_t*>(TargetPtr);
++    Value += Addend;
++    *TargetPtr8 = Value;
++    break;
++  case ELF::R_SPARC_16:
++    TargetPtr16 = reinterpret_cast<uint16_t*>(TargetPtr);
++    Value += Addend;
++    *TargetPtr16 = Value;
++    break;
++  case ELF::R_SPARC_32:
++  case ELF::R_SPARC_GLOB_DAT:
++    Value += Addend;
++    *TargetPtr = Value;
++    break;
++  case ELF::R_SPARC_JMP_SLOT:
++    break;
++  case ELF::R_SPARC_TLS_DTPOFF32:
++    Value += Addend;
++    *TargetPtr = Value;
++    break;
++  case ELF::R_SPARC_TLS_TPOFF32:
++    Value += Addend;
++    *TargetPtr = Value - Offset;
++    break;
++  case ELF::R_SPARC_TLS_LE_HIX22:
++    Value -= Offset;
++    Value += Addend;
++    *TargetPtr = (*TargetPtr & 0xFFC00000) | ((~Value) & 0x003FFFFFLL);
++    break;
++  case ELF::R_SPARC_TLS_LE_LOX10:
++    Value -= Offset;
++    Value += Addend;
++    *TargetPtr = (*TargetPtr & 0xFFFFE000) | (Value & 0x000003FFLL);
++    break;
++  case ELF::R_SPARC_DISP8:
++    Value += Addend;
++    TargetPtr8 = reinterpret_cast<uint8_t*>(TargetAddress);
++    *TargetPtr8 = (Value - reinterpret_cast<uintptr_t>(TargetPtr8));
++    break;
++  case ELF::R_SPARC_DISP16:
++    Value += Addend;
++    TargetPtr16 = reinterpret_cast<uint16_t*>(TargetAddress);
++    *TargetPtr16 = (Value - reinterpret_cast<uintptr_t>(TargetPtr16));
++    break;
++  case ELF::R_SPARC_DISP32:
++    Value += Addend;
++    TargetPtr32 = reinterpret_cast<uint32_t*>(TargetAddress);
++    *TargetPtr32 = (Value - reinterpret_cast<uintptr_t>(TargetPtr32));
++    break;
++  case ELF::R_SPARC_WDISP30:
++  case ELF::R_SPARC_WDISP22:
++  case ELF::R_SPARC_WDISP19:
++  case ELF::R_SPARC_WDISP16:
++  case ELF::R_SPARC_WDISP10:
++    switch (Type) {
++    default:
++      llvm_unreachable("Impossible default case!");
++      break;
++    case ELF::R_SPARC_WDISP30:
++      RS = 2;
++      RM = 0x3FFFFFFF;
++      break;
++    case ELF::R_SPARC_WDISP22:
++      RS = 2;
++      RM = 0x003FFFFF;
++      break;
++    case ELF::R_SPARC_WDISP19:
++      RS = 2;
++      RM = 0x0007FFFF;
++      break;
++    case ELF::R_SPARC_WDISP16:
++      RS = 2;
++      break;
++    case ELF::R_SPARC_WDISP10:
++      RS = 2;
++      break;
++    }
++
++    TargetPtr32 = reinterpret_cast<uint32_t*>(TargetPtr);
++    Reloc = (((Value + Addend) - LoadAddress) >> RS);
++    TargetValue = *TargetPtr32;
++
++    switch (Type) {
++    default:
++      llvm_unreachable("Impossible default case!");
++      break;
++    case ELF::R_SPARC_WDISP16:
++      TargetValue &= ~((0x3 << 20) | 0x3FFF);
++      Reloc = (((Reloc & 0xC000) << (7 - 1)) | (Reloc & 0x3FFFF));
++      *TargetPtr32 = TargetValue | Reloc;
++      break;
++    case ELF::R_SPARC_WDISP10:
++      TargetValue &= ~((0x3 << 19) | (0xFF << 5));
++      Reloc = (((Reloc & 0x300) << (13 - 2)) | ((Reloc & 0xFF) | (7 - 2)));
++      *TargetPtr32 = TargetValue | Reloc;
++      break;
++    case ELF::R_SPARC_WDISP30:
++    case ELF::R_SPARC_WDISP22:
++    case ELF::R_SPARC_WDISP19:
++      TargetValue &= ~RM;
++      Reloc &= RM;
++      *TargetPtr32 = TargetValue | Reloc;
++      break;
++    }
++    break;
++  case ELF::R_SPARC_HI22:
++    TargetPtr32 = reinterpret_cast<uint32_t*>(TargetPtr);
++    RS = 10;
++    RM = 0x003FFFFF;
++    Reloc = (Value + Addend) >> RS;
++    TargetValue = *TargetPtr32;
++    TargetValue &= ~RM;
++    Reloc &= RM;
++    *TargetPtr32 = TargetValue | Reloc;
++    break;
++  case ELF::R_SPARC_10:
++    Value += Addend;
++    TargetPtr32 = reinterpret_cast<uint32_t*>(TargetPtr);
++    *TargetPtr32 = Value;
++    break;
++  case ELF::R_SPARC_11:
++    Value += Addend;
++    TargetPtr32 = reinterpret_cast<uint32_t*>(TargetPtr);
++    *TargetPtr32 = Value;
++    break;
++  case ELF::R_SPARC_13:
++    Value += Addend;
++    TargetPtr32 = reinterpret_cast<uint32_t*>(TargetPtr);
++    *TargetPtr32 = Value;
++    break;
++  case ELF::R_SPARC_22:
++    Value += Addend;
++    TargetPtr32 = reinterpret_cast<uint32_t*>(TargetPtr);
++    *TargetPtr32 = Value;
++    break;
++  case ELF::R_SPARC_LO10:
++    TargetPtr32 = reinterpret_cast<uint32_t*>(TargetPtr);
++    RS = 0;
++    RM = 0x000003FF;
++    Reloc = (Value + Addend) >> RS;
++    TargetValue = *TargetPtr32;
++    TargetValue &= ~RM;
++    Reloc &= RM;
++    *TargetPtr32 = TargetValue | Reloc;
++    break;
++  case ELF::R_SPARC_LM22:
++    TargetPtr32 = reinterpret_cast<uint32_t*>(TargetPtr);
++    RS = 10;
++    RM = 0x003FFFFF;
++    Reloc = (Value + Addend) >> RS;
++    TargetValue = *TargetPtr32;
++    TargetValue &= ~RM;
++    Reloc &= RM;
++    *TargetPtr32 = TargetValue | Reloc;
++    break;
++  case ELF::R_SPARC_HIX22:
++    TargetPtr32 = reinterpret_cast<uint32_t*>(TargetPtr);
++    RS = 10;
++    RM = 0x3FFFFF;
++    Reloc = Value + Addend;
++    TargetValue = *TargetPtr32;
++    TargetValue &= ~RM;
++    Reloc ^= ~0;
++    Reloc >>= RS;
++    Reloc &= RM;
++    *TargetPtr32 = TargetValue | Reloc;
++    break;
++  case ELF::R_SPARC_LOX10:
++    TargetPtr32 = reinterpret_cast<uint32_t*>(TargetPtr);
++    Reloc = Value + Addend;
++    TargetValue = *TargetPtr32;
++    TargetValue &= ~0x1FFF;
++    Reloc &= 0x3FF;
++    Reloc |= 0x1C00;
++    *TargetPtr32 = TargetValue | Reloc;
++    break;
++  case ELF::R_SPARC_HH22:
++    TargetPtr32 = reinterpret_cast<uint32_t*>(TargetPtr);
++    RS = 42;
++    RM = 0x003FFFFF;
++    Reloc = (Value + Addend) >> RS;
++    TargetValue = *TargetPtr32;
++    TargetValue &= ~RM;
++    Reloc &= RM;
++    *TargetPtr32 = TargetValue | Reloc;
++    break;
++  case ELF::R_SPARC_HM10:
++    TargetPtr32 = reinterpret_cast<uint32_t*>(TargetPtr);
++    RS = 32;
++    RM = 0x000003FF;
++    Reloc = (Value + Addend) >> RS;
++    TargetValue = *TargetPtr32;
++    TargetValue &= ~RM;
++    Reloc &= RM;
++    *TargetPtr32 = TargetValue | Reloc;
++    break;
++  case ELF::R_SPARC_H44:
++    TargetPtr32 = reinterpret_cast<uint32_t*>(TargetPtr);
++    RS = 22;
++    RM = 0x003FFFFF;
++    Reloc = (Value + Addend) >> RS;
++    TargetValue = *TargetPtr32;
++    TargetValue &= ~RM;
++    Reloc &= RM;
++    *TargetPtr32 = TargetValue | Reloc;
++    break;
++  case ELF::R_SPARC_M44:
++    TargetPtr32 = reinterpret_cast<uint32_t*>(TargetPtr);
++    RS = 12;
++    RM = 0x000003FF;
++    Reloc = (Value + Addend) >> RS;
++    TargetValue = *TargetPtr32;
++    TargetValue &= ~RM;
++    Reloc &= RM;
++    *TargetPtr32 = TargetValue | Reloc;
++    break;
++  case ELF::R_SPARC_L44:
++    TargetPtr32 = reinterpret_cast<uint32_t*>(TargetPtr);
++    RS = 0;
++    RM = 0x00000FFF;
++    Reloc = (Value + Addend) >> RS;
++    TargetValue = *TargetPtr32;
++    TargetValue &= ~RM;
++    Reloc &= RM;
++    *TargetPtr32 = TargetValue | Reloc;
++    break;
++  case ELF::R_SPARC_GOT10:
++    assert((Offset != static_cast<uint64_t>(-1)) &&
++           "R_SPARC_GOT10: Invalid offset!");
++    if ((Offset & 1) != 0)
++      Offset &= ~1;
++    else
++      Offset |= 1;
++
++    RS = 0;
++    RM = 0x000003FF;
++    Reloc = (Value + Addend) >> RS;
++    TargetPtr32 = reinterpret_cast<uint32_t*>(TargetPtr);
++    TargetValue = *TargetPtr32;
++    TargetValue &= ~RM;
++    Reloc &= RM;
++    *TargetPtr32 = TargetValue | Reloc;
++    break;
++  case ELF::R_SPARC_GOT13:
++    assert((Offset != static_cast<uint64_t>(-1)) &&
++           "R_SPARC_GOT13: Invalid offset!");
++    if ((Offset & 1) != 0)
++      Offset &= ~1;
++    else
++      Offset |= 1;
++
++    RS = 0;
++    RM = 0x00001FFF;
++    Reloc = (Value + Addend) >> RS;
++
++    TargetPtr32 = reinterpret_cast<uint32_t*>(TargetPtr);
++    TargetValue = *TargetPtr32;
++    TargetValue &= ~RM;
++    Reloc &= RM;
++    *TargetPtr32 = TargetValue | Reloc;
++    break;
++  case ELF::R_SPARC_GOT22:
++    assert((Offset != static_cast<uint64_t>(-1)) &&
++           "R_SPARC_GOT22: Invalid offset!");
++    if ((Offset & 1) != 0)
++      Offset &= ~1;
++    else
++      Offset |= 1;
++
++    TargetPtr32 = reinterpret_cast<uint32_t*>(TargetPtr);
++    RS = 10;
++    RM = 0x003FFFFF;
++    Reloc = (Value + Addend) >> RS;
++    TargetValue = *TargetPtr32;
++    TargetValue &= ~RM;
++    Reloc &= RM;
++    *TargetPtr32 = TargetValue | Reloc;
++    break;
++  case ELF::R_SPARC_PC10:
++    TargetPtr32 = reinterpret_cast<uint32_t*>(TargetPtr);
++    RS = 0;
++    RM =0x000003FF;
++    Reloc = ((Value + Addend) - LoadAddress) >> RS;
++    TargetValue = *TargetPtr32;
++    TargetValue &= ~RM;
++    Reloc &= RM;
++    *TargetPtr32 = TargetValue | Reloc;
++    break;
++  case ELF::R_SPARC_PC22:
++    TargetPtr32 = reinterpret_cast<uint32_t*>(TargetPtr);
++    RS = 10;
++    RM = 0x003FFFFF;
++    Reloc = ((Value + Addend) - LoadAddress) >> RS;
++    TargetValue = *TargetPtr32;
++    TargetValue &= ~RM;
++    Reloc &= RM;
++    *TargetPtr32 = TargetValue | Reloc;
++    break;
++  case ELF::R_SPARC_UA16:
++    TargetPtr8 = reinterpret_cast<uint8_t*>(TargetPtr);
++    TargetPtr8[0] = Value >> 8U;
++    TargetPtr8[1] = Value;
++    break;
++  case ELF::R_SPARC_UA32:
++    TargetPtr8 = reinterpret_cast<uint8_t*>(TargetPtr);
++    TargetPtr8[0] = Value >> 24U;
++    TargetPtr8[1] = Value >> 16U;
++    TargetPtr8[2] = Value >> 8U;
++    TargetPtr8[3] = Value;
++    break;
++  case ELF::R_SPARC_WPLT30:
++    TargetPtr32 = reinterpret_cast<uint32_t*>(TargetPtr);
++    RS = 2;
++    RM = 0x3FFFFFFF;
++    Reloc = ((Value + Addend) - LoadAddress) >> RS;
++    TargetValue = *TargetPtr32;
++    TargetValue &= ~RM;
++    Reloc &= RM;
++    *TargetPtr32 = TargetValue | Reloc;
++    TargetValue = *TargetPtr32;
++    break;
++  }
++}
++
++/// SPARCV9 ELF Relocatinos - valid in 64-bit only.
++/// https://docs.oracle.com/cd/E19683-01/817-3677/chapter6-24-1/index.html
++void RuntimeDyldELF::resolveSPARC64Relocation(const SectionEntry &Section,
++                                              uint64_t Offset, uint64_t Value,
++                                              uint32_t Type, int64_t Addend) {
++  uint64_t *TargetAddress =
++    reinterpret_cast<uint64_t*>(reinterpret_cast<void*>(Section.getAddress()));
++  uint64_t *TargetPtr =
++    reinterpret_cast<uint64_t*>(Section.getAddressWithOffset(Offset));
++  uint32_t Reloc;
++  uintptr_t TargetPtrVal = reinterpret_cast<uintptr_t>(TargetPtr);
++  uint8_t *TargetPtr8 = nullptr;
++  uint16_t *TargetPtr16 = nullptr;
++  uint32_t *TargetPtr32 = nullptr;
++  uint64_t LoadAddress = Section.getLoadAddressWithOffset(Offset);
++  uint64_t TargetValue = 0ULL;
++  int32_t RS;
++  int32_t RM;
++
++  switch (Type) {
++  case ELF::R_SPARC_HI22:
++    TargetPtr32 = reinterpret_cast<uint32_t*>(TargetPtr);
++    RS = 10;
++    RM = 0x003FFFFF;
++    Reloc = (Value + Addend) >> RS;
++    TargetValue = *TargetPtr32;
++    TargetValue &= ~RM;
++    Reloc &= RM;
++    *TargetPtr32 = TargetValue | Reloc;
++    break;
++  case ELF::R_SPARC_64:
++  case ELF::R_SPARC_GLOB_DAT:
++    Value += Addend;
++    *TargetPtr = Value;
++    break;
++  case ELF::R_SPARC_RELATIVE:
++    *TargetPtr = LoadAddress + Addend;
++    break;
++  case ELF::R_SPARC_OLO10:
++    TargetPtr32 = reinterpret_cast<uint32_t*>(TargetPtr);
++    *TargetPtr32 = (*TargetPtr32 & ~0x1FFF) | (((Value + Addend) & 0x3FF) +
++                                               ((Offset >> 8) & 0x1FFF));
++    break;
++  case ELF::R_SPARC_DISP64:
++    Value += Addend;
++    *TargetPtr = (Value - reinterpret_cast<uintptr_t>(TargetPtr));
++    break;
++  case ELF::R_SPARC_REGISTER:
++    Value += Addend;
++    *TargetPtr = Value;
++    break;
++  case ELF::R_SPARC_PLT64:
++    llvm::errs() << __PRETTY_FUNCTION__
++      << ": Warning: Unimplemented R_SPARC_PLT64 Relocation type.\n" ;
++    break;
++  case ELF::R_SPARC_UA64:
++    Value += Addend;
++    if (0 == (TargetPtrVal & 3)) {
++      TargetPtr32 = reinterpret_cast<uint32_t*>(TargetPtr);
++      TargetPtr32[0] = Value >> 32;
++      TargetPtr32[1] = Value;
++    } else {
++      TargetPtr8 = reinterpret_cast<uint8_t*>(TargetPtr);
++      TargetPtr8[0] = Value >> 56;
++      TargetPtr8[0] = Value >> 48;
++      TargetPtr8[0] = Value >> 40;
++      TargetPtr8[0] = Value >> 32;
++      TargetPtr8[0] = Value >> 24;
++      TargetPtr8[0] = Value >> 16;
++      TargetPtr8[0] = Value >> 8;
++      TargetPtr8[0] = Value;
++    }
++    break;
++  default:
++    resolveSPARC3264Relocation(Section, Offset, Value, Type, Addend);
++    break;
++  }
++}
++
+ void RuntimeDyldELF::resolveSystemZRelocation(const SectionEntry &Section,
+                                               uint64_t Offset, uint64_t Value,
+                                               uint32_t Type, int64_t Addend) {
+@@ -1123,6 +1565,12 @@
+   case Triple::systemz:
+     resolveSystemZRelocation(Section, Offset, Value, Type, Addend);
+     break;
++  case Triple::sparc:
++    resolveSPARC3264Relocation(Section, Offset, Value, Type, Addend);
++    break;
++  case Triple::sparcv9:
++    resolveSPARC64Relocation(Section, Offset, Value, Type, Addend);
++    break;
+   default:
+     llvm_unreachable("Unsupported CPU type!");
+   }
+@@ -1590,6 +2038,160 @@
+       else
+         addRelocationForSection(RE, Value.SectionID);
+     }
++  } else if (Arch == Triple::sparc) {
++    DEBUG(dbgs() << "This is a SPARC32 relocation.\n");
++    SectionEntry &Section = Sections[SectionID];
++    uint8_t *Target = Section.getAddressWithOffset(Offset);
++    uint32_t *TargetAddress = reinterpret_cast<uint32_t*>(Target);
++    uint8_t *SectionAddress = Section.getAddress();
++    uintptr_t StubOffset = Section.getStubOffset();
++    uintptr_t StubAddress = static_cast<uintptr_t>(-1);
++
++    if (RelType == ELF::R_SPARC_WDISP30) {
++      //  Look up for existing stub.
++      StubMap::const_iterator i = Stubs.find(Value);
++
++      if (i != Stubs.end()) {
++        DEBUG(dbgs() << " Stub function found\n");
++        StubAddress =
++          reinterpret_cast<uintptr_t>(Section.getAddressWithOffset(i->second));
++
++        resolveRelocation(Section, Offset, StubAddress, RelType, 0);
++        Section.advanceStubOffset(getMaxStubSize());
++      } else {
++        // Create a new stub function.
++        DEBUG(dbgs() << " Create a new stub function\n");
++
++        uintptr_t BaseAddress =
++          reinterpret_cast<uintptr_t>(Section.getAddress());
++        uintptr_t StubAlignment = getStubAlignment();
++        StubAddress = BaseAddress + StubOffset;
++        StubAddress = llvm::RoundUpToAlignment(StubAddress, 4U);
++        StubOffset = StubAddress - BaseAddress;
++
++        Stubs[Value] = StubOffset;
++        uint8_t *StubTargetAddr =
++          createStubFunction(reinterpret_cast<uint8_t*>(StubAddress));
++
++        // Creating Hi and Lo relocations for the filled stub instructions.
++        RelocationEntry REhi(SectionID,
++                             StubTargetAddr - SectionAddress,
++                             ELF::R_SPARC_HI22, Value.Addend);
++        RelocationEntry RElo(SectionID,
++                             StubTargetAddr - SectionAddress + 4,
++                             ELF::R_SPARC_LO10, Value.Addend);
++
++        if (Value.SymbolName) {
++          addRelocationForSymbol(REhi, Value.SymbolName);
++          addRelocationForSymbol(RElo, Value.SymbolName);
++        } else {
++          addRelocationForSection(REhi, Value.SectionID);
++          addRelocationForSection(RElo, Value.SectionID);
++        }
++
++        resolveRelocation(Section, Offset, StubAddress, RelType, 0);
++        Section.advanceStubOffset(getMaxStubSize());
++      }
++    } else {
++      uintptr_t BaseAddress =
++        reinterpret_cast<uintptr_t>(Section.getAddress());
++      uintptr_t StubAlignment = getStubAlignment();
++      StubAddress = BaseAddress + StubOffset;
++      StubAddress = llvm::RoundUpToAlignment(StubAddress, 4U);
++      StubOffset = StubAddress - BaseAddress;
++
++      RelocationEntry RE(SectionID, Offset, RelType, Addend);
++      if (Value.SymbolName)
++        addRelocationForSymbol(RE, Value.SymbolName);
++      else
++        addRelocationForSection(RE, Value.SectionID);
++
++      resolveRelocation(Section, Offset, StubOffset, RelType, 0);
++      Section.advanceStubOffset(getMaxStubSize());
++    }
++  } else if (Arch == Triple::sparcv9) {
++    DEBUG(dbgs() << "This is a SPARC64 relocation.\n");
++
++    SectionEntry &Section = Sections[SectionID];
++    uint8_t *Target = Section.getAddressWithOffset(Offset);
++    uint32_t *TargetAddress = reinterpret_cast<uint32_t*>(Target);
++    uint8_t *SectionAddress = Section.getAddress();
++    uintptr_t StubOffset = Section.getStubOffset();
++    uintptr_t StubAddress = static_cast<uintptr_t>(-1);
++
++    if (RelType == ELF::R_SPARC_WDISP30) {
++      //  Look up for existing stub.
++      StubMap::const_iterator i = Stubs.find(Value);
++      if (i != Stubs.end()) {
++        DEBUG(dbgs() << " Stub function found\n");
++
++        StubAddress =
++          reinterpret_cast<uintptr_t>(Section.getAddressWithOffset(i->second));
++
++        resolveRelocation(Section, Offset, StubAddress, RelType, 0);
++        Section.advanceStubOffset(getMaxStubSize());
++      } else {
++        // Create a new stub function.
++        DEBUG(dbgs() << " Create a new stub function\n");
++
++        uintptr_t BaseAddress =
++          reinterpret_cast<uintptr_t>(Section.getAddress());
++        uintptr_t StubAlignment = getStubAlignment();
++
++        StubAddress = BaseAddress + StubOffset;
++        StubAddress = llvm::RoundUpToAlignment(StubAddress, 8U);
++        StubOffset = StubAddress - BaseAddress;
++        Stubs[Value] = StubOffset;
++
++        uint8_t *StubTargetAddr =
++          createStubFunction(reinterpret_cast<uint8_t*>(StubAddress));
++
++        // Creating Hi and Lo relocations for the filled stub instructions.
++        RelocationEntry REhh(SectionID,
++                             StubTargetAddr - SectionAddress,
++                             ELF::R_SPARC_HH22, Value.Addend);
++        RelocationEntry REhm(SectionID,
++                             StubTargetAddr - SectionAddress + 8,
++                             ELF::R_SPARC_HM10, Value.Addend);
++        RelocationEntry RElm(SectionID,
++                             StubTargetAddr - SectionAddress + 16,
++                             ELF::R_SPARC_LM22, Value.Addend);
++        RelocationEntry RElo(SectionID,
++                             StubTargetAddr - SectionAddress + 24,
++                             ELF::R_SPARC_LO10, Value.Addend);
++
++        if (Value.SymbolName) {
++          addRelocationForSymbol(REhh, Value.SymbolName);
++          addRelocationForSymbol(REhm, Value.SymbolName);
++          addRelocationForSymbol(RElm, Value.SymbolName);
++          addRelocationForSymbol(RElo, Value.SymbolName);
++        } else {
++          addRelocationForSection(REhh, Value.SectionID);
++          addRelocationForSection(REhm, Value.SectionID);
++          addRelocationForSection(RElm, Value.SectionID);
++          addRelocationForSection(RElo, Value.SectionID);
++        }
++
++        resolveRelocation(Section, Offset, StubAddress, RelType, 0);
++        Section.advanceStubOffset(getMaxStubSize());
++      }
++    } else {
++      uintptr_t BaseAddress =
++        reinterpret_cast<uintptr_t>(Section.getAddress());
++      uintptr_t StubAlignment = getStubAlignment();
++      StubAddress = BaseAddress + StubOffset;
++      StubAddress = llvm::RoundUpToAlignment(StubAddress, 8U);
++      StubOffset = StubAddress - BaseAddress;
++
++      RelocationEntry RE(SectionID, Offset, RelType, Addend);
++      if (Value.SymbolName)
++        addRelocationForSymbol(RE, Value.SymbolName);
++      else
++        addRelocationForSection(RE, Value.SectionID);
++
++      resolveRelocation(Section, Offset, StubAddress, RelType, 0);
++      Section.advanceStubOffset(getMaxStubSize());
++    }
+   } else if (Arch == Triple::systemz &&
+              (RelType == ELF::R_390_PLT32DBL || RelType == ELF::R_390_GOTENT)) {
+     // Create function stubs for both PLT and GOT references, regardless of
+###
+--- lib/ExecutionEngine/ExecutionEngine.cpp	2015-10-13 10:11:02.000000000 -0800
++++ lib/ExecutionEngine/ExecutionEngine.cpp	2016-07-04 21:13:53.782045325 -0800
+@@ -36,9 +36,12 @@
+ #include "llvm/Support/TargetRegistry.h"
+ #include "llvm/Support/raw_ostream.h"
+ #include "llvm/Target/TargetMachine.h"
++
++using namespace llvm;
++
+ #include <cmath>
+ #include <cstring>
+-using namespace llvm;
++#include <memory>
+ 
+ #define DEBUG_TYPE "jit"
+ 
+@@ -326,46 +329,57 @@
+   return nullptr;
+ }
+ 
++// Why is this in the anon namespace?
+ namespace {
+ class ArgvArray {
+   std::unique_ptr<char[]> Array;
+   std::vector<std::unique_ptr<char[]>> Values;
++
+ public:
++  ArgvArray() : Array(), Values() { }
++  ~ArgvArray() { }
++
+   /// Turn a vector of strings into a nice argv style array of pointers to null
+   /// terminated strings.
+   void *reset(LLVMContext &C, ExecutionEngine *EE,
+               const std::vector<std::string> &InputArgv);
+ };
+ }  // anonymous namespace
++
+ void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
+                        const std::vector<std::string> &InputArgv) {
+-  Values.clear();  // Free the old contents.
+-  Values.reserve(InputArgv.size());
++  Values.clear();  // Free the old contents.
++  Values.resize(InputArgv.size() + 1);
+   unsigned PtrSize = EE->getDataLayout().getPointerSize();
+-  Array = make_unique<char[]>((InputArgv.size()+1)*PtrSize);
++  Array = make_unique<char[]>((InputArgv.size() + 1) * PtrSize);
+ 
+   DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array.get() << "\n");
++
+   Type *SBytePtr = Type::getInt8PtrTy(C);
+ 
+   for (unsigned i = 0; i != InputArgv.size(); ++i) {
+-    unsigned Size = InputArgv[i].size()+1;
++    unsigned Size = InputArgv[i].size() + 1;
+     auto Dest = make_unique<char[]>(Size);
+-    DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest.get() << "\n");
++
++    DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*) Dest.get() << "\n");
+ 
+     std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest.get());
+-    Dest[Size-1] = 0;
++    Dest[Size - 1] = '\0';
++    GenericValue *GVP =
++      reinterpret_cast<GenericValue*>(&Array[i * PtrSize]);
+ 
+     // Endian safe: Array[i] = (PointerTy)Dest;
+-    EE->StoreValueToMemory(PTOGV(Dest.get()),
+-                           (GenericValue*)(&Array[i*PtrSize]), SBytePtr);
++    EE->StoreValueToMemory(PTOGV(Dest.get()), GVP, SBytePtr);
+     Values.push_back(std::move(Dest));
+   }
+ 
++  GenericValue *GVT =
++    reinterpret_cast<GenericValue*>(&Array[InputArgv.size() * PtrSize]);
++
+   // Null terminate it
+-  EE->StoreValueToMemory(PTOGV(nullptr),
+-                         (GenericValue*)(&Array[InputArgv.size()*PtrSize]),
+-                         SBytePtr);
+-  return Array.get();
++  EE->StoreValueToMemory(PTOGV(0L), GVT, SBytePtr);
++  void *Retval = Array.get();
++  return Retval;
+ }
+ 
+ void ExecutionEngine::runStaticConstructorsDestructors(Module &module,
+@@ -425,16 +439,17 @@
+ #endif
+ 
+ int ExecutionEngine::runFunctionAsMain(Function *Fn,
+-                                       const std::vector<std::string> &argv,
+-                                       const char * const * envp) {
++                                       const std::vector<std::string> &Argv,
++                                       const char* const *Envp) {
++  LLVMContext &Ctx = Fn->getContext();
+   std::vector<GenericValue> GVArgs;
+   GenericValue GVArgc;
+-  GVArgc.IntVal = APInt(32, argv.size());
++  GVArgc.IntVal = APInt(32, Argv.size());
+ 
+   // Check main() type
+   unsigned NumArgs = Fn->getFunctionType()->getNumParams();
+   FunctionType *FTy = Fn->getFunctionType();
+-  Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
++  Type* PPInt8Ty = Type::getInt8PtrTy(Ctx)->getPointerTo();
+ 
+   // Check the argument types.
+   if (NumArgs > 3)
+@@ -451,19 +466,20 @@
+ 
+   ArgvArray CArgv;
+   ArgvArray CEnv;
++
+   if (NumArgs) {
+     GVArgs.push_back(GVArgc); // Arg #0 = argc.
+     if (NumArgs > 1) {
+       // Arg #1 = argv.
+-      GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
++      GVArgs.push_back(PTOGV(CArgv.reset(Ctx, this, Argv)));
+       assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
+              "argv[0] was null after CreateArgv");
+       if (NumArgs > 2) {
+         std::vector<std::string> EnvVars;
+-        for (unsigned i = 0; envp[i]; ++i)
+-          EnvVars.emplace_back(envp[i]);
++        for (unsigned i = 0; Envp[i]; ++i)
++          EnvVars.emplace_back(Envp[i]);
+         // Arg #2 = envp.
+-        GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
++        GVArgs.push_back(PTOGV(CEnv.reset(Ctx, this, EnvVars)));
+       }
+     }
+   }
+###
+--- lib/ExecutionEngine/MCJIT/MCJIT.cpp	2015-11-05 10:24:56.000000000 -0900
++++ lib/ExecutionEngine/MCJIT/MCJIT.cpp	2016-07-04 09:15:17.759594945 -0800
+@@ -43,34 +43,37 @@
+ }
+ 
+ ExecutionEngine*
+-MCJIT::createJIT(std::unique_ptr<Module> M,
++MCJIT::createJIT(std::unique_ptr<Module> MIn,
+                  std::string *ErrorStr,
+-                 std::shared_ptr<MCJITMemoryManager> MemMgr,
+-                 std::shared_ptr<RuntimeDyld::SymbolResolver> Resolver,
+-                 std::unique_ptr<TargetMachine> TM) {
++                 std::shared_ptr<MCJITMemoryManager> MemMgrIn,
++                 std::shared_ptr<RuntimeDyld::SymbolResolver> ResolverIn,
++                 std::unique_ptr<TargetMachine> TMIn) {
+   // Try to register the program as a source of symbols to resolve against.
+   //
+   // FIXME: Don't do this here.
+   sys::DynamicLibrary::LoadLibraryPermanently(nullptr, nullptr);
+ 
+-  if (!MemMgr || !Resolver) {
++  if (!MemMgrIn || !ResolverIn) {
+     auto RTDyldMM = std::make_shared<SectionMemoryManager>();
+-    if (!MemMgr)
+-      MemMgr = RTDyldMM;
+-    if (!Resolver)
+-      Resolver = RTDyldMM;
+-  }
+-
+-  return new MCJIT(std::move(M), std::move(TM), std::move(MemMgr),
+-                   std::move(Resolver));
+-}
+-
+-MCJIT::MCJIT(std::unique_ptr<Module> M, std::unique_ptr<TargetMachine> TM,
+-             std::shared_ptr<MCJITMemoryManager> MemMgr,
+-             std::shared_ptr<RuntimeDyld::SymbolResolver> Resolver)
+-    : ExecutionEngine(TM->createDataLayout(), std::move(M)), TM(std::move(TM)),
+-      Ctx(nullptr), MemMgr(std::move(MemMgr)),
+-      Resolver(*this, std::move(Resolver)), Dyld(*this->MemMgr, this->Resolver),
++    if (!MemMgrIn)
++      MemMgrIn = RTDyldMM;
++    if (!ResolverIn)
++      ResolverIn = RTDyldMM;
++  }
++
++  return new MCJIT(std::move(MIn), std::move(TMIn), std::move(MemMgrIn),
++                   std::move(ResolverIn));
++}
++
++MCJIT::MCJIT(std::unique_ptr<Module> MIn,
++             std::unique_ptr<TargetMachine> TMIn,
++             std::shared_ptr<MCJITMemoryManager> MemMgrIn,
++             std::shared_ptr<RuntimeDyld::SymbolResolver> ResolverIn)
++    : ExecutionEngine(TMIn->createDataLayout(), std::move(MIn)),
++      TM(std::move(TMIn)),
++      Ctx(nullptr), MemMgr(std::move(MemMgrIn)),
++      Resolver(*this, std::move(ResolverIn)),
++      Dyld(*this->MemMgr, this->Resolver),
+       ObjCache(nullptr) {
+   // FIXME: We are managing our modules, so we do not want the base class
+   // ExecutionEngine to manage them as well. To avoid double destruction
+@@ -85,6 +88,7 @@
+   std::unique_ptr<Module> First = std::move(Modules[0]);
+   Modules.clear();
+ 
++  First->setDataLayout(ExecutionEngine::getDataLayout());
+   OwnedModules.addModule(std::move(First));
+   RegisterJITEventListener(JITEventListener::createGDBRegistrationListener());
+ }
+@@ -148,7 +152,7 @@
+   legacy::PassManager PM;
+ 
+   // The RuntimeDyld will take ownership of this shortly
+-  SmallVector<char, 4096> ObjBufferSV;
++  SmallVector<char, 8192> ObjBufferSV;
+   raw_svector_ostream ObjStream(ObjBufferSV);
+ 
+   // Turn the machine code intermediate representation into bytes in memory
+@@ -158,8 +162,8 @@
+ 
+   // Initialize passes.
+   PM.run(*M);
+-  // Flush the output buffer to get the generated code into memory
+ 
++  // Flush the output buffer to get the generated code into memory
+   std::unique_ptr<MemoryBuffer> CompiledObjBuffer(
+                                 new ObjectMemoryBuffer(std::move(ObjBufferSV)));
+ 
+@@ -380,7 +384,7 @@
+   MutexGuard locked(lock);
+ 
+   Mangler Mang;
+-  SmallString<128> Name;
++  SmallString<512> Name;
+   TM->getNameWithPrefix(Name, F, Mang);
+ 
+   if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
+@@ -391,7 +395,8 @@
+   }
+ 
+   Module *M = F->getParent();
+-  bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
++  bool HasBeenAddedButNotLoaded =
++    OwnedModules.hasModuleBeenAddedButNotLoaded(M);
+ 
+   // Make sure the relevant module has been compiled and loaded.
+   if (HasBeenAddedButNotLoaded)
+@@ -439,10 +444,11 @@
+   return nullptr;
+ }
+ 
+-GlobalVariable *MCJIT::FindGlobalVariableNamedInModulePtrSet(const char *Name,
+-                                                             bool AllowInternal,
+-                                                             ModulePtrSet::iterator I,
+-                                                             ModulePtrSet::iterator E) {
++GlobalVariable*
++MCJIT::FindGlobalVariableNamedInModulePtrSet(const char *Name,
++                                             bool AllowInternal,
++                                             ModulePtrSet::iterator I,
++                                             ModulePtrSet::iterator E) {
+   for (; I != E; ++I) {
+     GlobalVariable *GV = (*I)->getGlobalVariable(Name, AllowInternal);
+     if (GV && !GV->isDeclaration())
+@@ -453,8 +459,9 @@
+ 
+ 
+ Function *MCJIT::FindFunctionNamed(const char *FnName) {
+-  Function *F = FindFunctionNamedInModulePtrSet(
+-      FnName, OwnedModules.begin_added(), OwnedModules.end_added());
++  Function *F =
++    FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_added(),
++                                    OwnedModules.end_added());
+   if (!F)
+     F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
+                                         OwnedModules.end_loaded());
+@@ -464,15 +471,20 @@
+   return F;
+ }
+ 
+-GlobalVariable *MCJIT::FindGlobalVariableNamed(const char *Name, bool AllowInternal) {
+-  GlobalVariable *GV = FindGlobalVariableNamedInModulePtrSet(
+-      Name, AllowInternal, OwnedModules.begin_added(), OwnedModules.end_added());
++GlobalVariable *MCJIT::FindGlobalVariableNamed(const char *Name,
++                                               bool AllowInternal) {
++  GlobalVariable *GV =
++    FindGlobalVariableNamedInModulePtrSet(Name, AllowInternal,
++                                          OwnedModules.begin_added(),
++                                          OwnedModules.end_added());
+   if (!GV)
+-    GV = FindGlobalVariableNamedInModulePtrSet(Name, AllowInternal, OwnedModules.begin_loaded(),
+-                                        OwnedModules.end_loaded());
++    GV = FindGlobalVariableNamedInModulePtrSet(Name, AllowInternal,
++                                               OwnedModules.begin_loaded(),
++                                               OwnedModules.end_loaded());
+   if (!GV)
+-    GV = FindGlobalVariableNamedInModulePtrSet(Name, AllowInternal, OwnedModules.begin_finalized(),
+-                                        OwnedModules.end_finalized());
++    GV = FindGlobalVariableNamedInModulePtrSet(Name, AllowInternal,
++                                               OwnedModules.begin_finalized(),
++                                               OwnedModules.end_finalized());
+   return GV;
+ }
+ 
+@@ -493,41 +505,57 @@
+   // Handle some common cases first.  These cases correspond to common `main'
+   // prototypes.
+   if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
++    int Argc;
++    char **Argv;
++    const char **Envp;
++    GenericValue RV;
++    RV.IntVal = APInt(32, 1);
++
+     switch (ArgValues.size()) {
+     case 3:
+       if (FTy->getParamType(0)->isIntegerTy(32) &&
+           FTy->getParamType(1)->isPointerTy() &&
+           FTy->getParamType(2)->isPointerTy()) {
+         int (*PF)(int, char **, const char **) =
+-          (int(*)(int, char **, const char **))(intptr_t)FPtr;
++          (int(*)(int, char **, const char **))(uintptr_t)FPtr;
++
++        Argc = ArgValues[0].IntVal.getZExtValue();
++        assert(Argc >= 1 && "Invalid argument count!");
++
++        Argv = reinterpret_cast<char**>(ArgValues[1].PointerVal);
++        Envp = reinterpret_cast<const char**>(ArgValues[2].PointerVal);
+ 
+         // Call the function.
+-        GenericValue rv;
+-        rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
+-                                 (char **)GVTOP(ArgValues[1]),
+-                                 (const char **)GVTOP(ArgValues[2])));
+-        return rv;
++        RV.IntVal = APInt(32, PF(Argc, Argv, Envp));
++        return RV;
+       }
+       break;
+     case 2:
+       if (FTy->getParamType(0)->isIntegerTy(32) &&
+           FTy->getParamType(1)->isPointerTy()) {
+-        int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
++        int (*PF)(int, char **) =
++          (int(*)(int, char **))(uintptr_t)FPtr;
++
++        Argc = ArgValues[0].IntVal.getZExtValue();
++        assert(Argc >= 1 && "Invalid argument count!");
++
++        Argv = reinterpret_cast<char**>(ArgValues[1].PointerVal);
+ 
+         // Call the function.
+-        GenericValue rv;
+-        rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
+-                                 (char **)GVTOP(ArgValues[1])));
+-        return rv;
++        RV.IntVal = APInt(32,  PF(Argc, Argv));
++        return RV;
+       }
+       break;
+     case 1:
+       if (FTy->getNumParams() == 1 &&
+           FTy->getParamType(0)->isIntegerTy(32)) {
+-        GenericValue rv;
+-        int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
+-        rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
+-        return rv;
++        int (*PF)(int) = (int(*)(int))(uintptr_t)FPtr;
++        Argc = ArgValues[0].IntVal.getZExtValue();
++        assert(Argc == 1 && "Invalid argument count!");
++
++        // Call the function.
++        RV.IntVal = APInt(32, PF(Argc));
++        return RV;
+       }
+       break;
+     }
+###
+--- include/llvm/Object/ELFObjectFile.h	2016-01-12 11:56:01.000000000 -0900
++++ include/llvm/Object/ELFObjectFile.h	2016-07-03 05:39:54.209691940 -0800
+@@ -840,8 +840,9 @@
+     case ELF::EM_PPC:
+       return "ELF32-ppc";
+     case ELF::EM_SPARC:
+-    case ELF::EM_SPARC32PLUS:
+       return "ELF32-sparc";
++    case ELF::EM_SPARC32PLUS:
++      return "ELF32-sparc32plus";
+     case ELF::EM_WEBASSEMBLY:
+       return "ELF32-wasm";
+     default:
+@@ -860,7 +861,7 @@
+     case ELF::EM_S390:
+       return "ELF64-s390";
+     case ELF::EM_SPARCV9:
+-      return "ELF64-sparc";
++      return "ELF64-sparcv9";
+     case ELF::EM_MIPS:
+       return "ELF64-mips";
+     case ELF::EM_WEBASSEMBLY:
+@@ -908,8 +909,8 @@
+     return Triple::systemz;
+ 
+   case ELF::EM_SPARC:
+-  case ELF::EM_SPARC32PLUS:
+     return IsLittleEndian ? Triple::sparcel : Triple::sparc;
++  case ELF::EM_SPARC32PLUS:
+   case ELF::EM_SPARCV9:
+     return Triple::sparcv9;
+   case ELF::EM_WEBASSEMBLY:
+###
+--- tools/lli/lli.cpp	2016-01-19 15:32:09.000000000 -0900
++++ tools/lli/lli.cpp	2016-07-03 18:17:05.510434280 -0800
+@@ -54,6 +54,8 @@
+ #include "llvm/Support/raw_ostream.h"
+ #include "llvm/Transforms/Instrumentation.h"
+ #include <cerrno>
++#include <string>
++#include <vector>
+ 
+ #ifdef __CYGWIN__
+ #include <cygwin/version.h>
+@@ -66,176 +68,179 @@
+ 
+ #define DEBUG_TYPE "lli"
+ 
+-namespace {
+ 
+-  enum class JITKind { MCJIT, OrcMCJITReplacement, OrcLazy };
++enum class JITKind { MCJIT, OrcMCJITReplacement, OrcLazy };
+ 
+-  cl::opt<std::string>
+-  InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
++static cl::opt<std::string>
++InputFile(cl::desc("<input bitcode>"), cl::Positional,
++          cl::init(std::string("-")));
++
++static cl::list<std::string>
++InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
++
++static cl::opt<bool>
++ForceInterpreter("force-interpreter",
++                 cl::desc("Force interpretation: disable JIT"),
++                 cl::init(false));
++
++static cl::opt<JITKind>
++UseJITKind("jit-kind",
++           cl::desc("Choose underlying JIT kind."),
++           cl::init(JITKind::MCJIT),
++           cl::values(
++             clEnumValN(JITKind::MCJIT, "mcjit",
++                        "MCJIT"),
++             clEnumValN(JITKind::OrcMCJITReplacement,
++                        "orc-mcjit",
++                        "Orc-based MCJIT replacement"),
++             clEnumValN(JITKind::OrcLazy,
++                        "orc-lazy",
++                        "Orc-based lazy JIT."),
++             clEnumValEnd));
++
++// The MCJIT supports building for a target address space separate from
++// the JIT compilation process. Use a forked process and a copying
++// memory manager with IPC to execute using this functionality.
++static cl::opt<bool>
++RemoteMCJIT("remote-mcjit",
++            cl::desc("Execute MCJIT'ed code in a separate process."),
++            cl::init(false));
++
++// Manually specify the child process for remote execution. This overrides
++// the simulated remote execution that allocates address space for child
++// execution. The child process will be executed and will communicate with
++// lli via stdin/stdout pipes.
++static cl::opt<std::string>
++ChildExecPath("mcjit-remote-process",
++              cl::desc("Specify the filename of the process to launch "
++                       "for remote MCJIT execution.  If none is specified,"
++                       "\n\tremote execution will be simulated in-process."),
++              cl::value_desc("filename"),
++              cl::init(std::string("")));
++
++// Determine optimization level.
++static cl::opt<char>
++OptLevel("O",
++         cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
++                  "(default = '-O2')"),
++         cl::Prefix,
++         cl::ZeroOrMore,
++         cl::init(' '));
++
++static cl::opt<std::string>
++TargetTriple("mtriple", cl::desc("Override target triple for module"));
++
++static cl::opt<std::string>
++MArch("march",
++      cl::desc("Architecture to generate assembly for (see --version)"));
++
++static cl::opt<std::string>
++MCPU("mcpu",
++     cl::desc("Target a specific cpu type (-mcpu=help for details)"),
++     cl::value_desc("cpu-name"),
++     cl::init(std::string("")));
++
++static cl::list<std::string>
++MAttrs("mattr",
++       cl::CommaSeparated,
++       cl::desc("Target specific attributes (-mattr=help for details)"),
++       cl::value_desc("a1,+a2,-a3,..."));
++
++static cl::opt<std::string>
++EntryFunc("entry-function",
++          cl::desc("Specify the entry function (default = 'main') "
++                   "of the executable"),
++          cl::value_desc("function"),
++          cl::init(std::string("main")));
++
++static cl::list<std::string>
++ExtraModules("extra-module",
++             cl::desc("Extra modules to be loaded"),
++             cl::value_desc("input bitcode"));
++
++static cl::list<std::string>
++ExtraObjects("extra-object",
++             cl::desc("Extra object files to be loaded"),
++             cl::value_desc("input object"));
++
++static cl::list<std::string>
++ExtraArchives("extra-archive",
++              cl::desc("Extra archive files to be loaded"),
++              cl::value_desc("input archive"));
++
++static cl::opt<bool>
++EnableCacheManager("enable-cache-manager",
++                   cl::desc("Use cache manager to save/load mdoules"),
++                   cl::init(false));
++
++static cl::opt<std::string>
++ObjectCacheDir("object-cache-dir",
++               cl::desc("Directory to store cached object files "
++                        "(must be user writable)"),
++               cl::init(std::string("")));
++
++static cl::opt<std::string>
++FakeArgv0("fake-argv0",
++          cl::desc("Override the 'argv[0]' value passed into the executing"
++                   " program"), cl::value_desc("executable"));
++
++static cl::opt<bool>
++DisableCoreFiles("disable-core-files", cl::Hidden,
++                 cl::desc("Disable emission of core files if possible"));
+ 
+-  cl::list<std::string>
+-  InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
+-
+-  cl::opt<bool> ForceInterpreter("force-interpreter",
+-                                 cl::desc("Force interpretation: disable JIT"),
+-                                 cl::init(false));
+-
+-  cl::opt<JITKind> UseJITKind("jit-kind",
+-                              cl::desc("Choose underlying JIT kind."),
+-                              cl::init(JITKind::MCJIT),
+-                              cl::values(
+-                                clEnumValN(JITKind::MCJIT, "mcjit",
+-                                           "MCJIT"),
+-                                clEnumValN(JITKind::OrcMCJITReplacement,
+-                                           "orc-mcjit",
+-                                           "Orc-based MCJIT replacement"),
+-                                clEnumValN(JITKind::OrcLazy,
+-                                           "orc-lazy",
+-                                           "Orc-based lazy JIT."),
+-                                clEnumValEnd));
+-
+-  // The MCJIT supports building for a target address space separate from
+-  // the JIT compilation process. Use a forked process and a copying
+-  // memory manager with IPC to execute using this functionality.
+-  cl::opt<bool> RemoteMCJIT("remote-mcjit",
+-    cl::desc("Execute MCJIT'ed code in a separate process."),
+-    cl::init(false));
+-
+-  // Manually specify the child process for remote execution. This overrides
+-  // the simulated remote execution that allocates address space for child
+-  // execution. The child process will be executed and will communicate with
+-  // lli via stdin/stdout pipes.
+-  cl::opt<std::string>
+-  ChildExecPath("mcjit-remote-process",
+-                cl::desc("Specify the filename of the process to launch "
+-                         "for remote MCJIT execution.  If none is specified,"
+-                         "\n\tremote execution will be simulated in-process."),
+-                cl::value_desc("filename"), cl::init(""));
+-
+-  // Determine optimization level.
+-  cl::opt<char>
+-  OptLevel("O",
+-           cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
+-                    "(default = '-O2')"),
+-           cl::Prefix,
+-           cl::ZeroOrMore,
+-           cl::init(' '));
+-
+-  cl::opt<std::string>
+-  TargetTriple("mtriple", cl::desc("Override target triple for module"));
+-
+-  cl::opt<std::string>
+-  MArch("march",
+-        cl::desc("Architecture to generate assembly for (see --version)"));
+-
+-  cl::opt<std::string>
+-  MCPU("mcpu",
+-       cl::desc("Target a specific cpu type (-mcpu=help for details)"),
+-       cl::value_desc("cpu-name"),
+-       cl::init(""));
+-
+-  cl::list<std::string>
+-  MAttrs("mattr",
+-         cl::CommaSeparated,
+-         cl::desc("Target specific attributes (-mattr=help for details)"),
+-         cl::value_desc("a1,+a2,-a3,..."));
+-
+-  cl::opt<std::string>
+-  EntryFunc("entry-function",
+-            cl::desc("Specify the entry function (default = 'main') "
+-                     "of the executable"),
+-            cl::value_desc("function"),
+-            cl::init("main"));
+-
+-  cl::list<std::string>
+-  ExtraModules("extra-module",
+-         cl::desc("Extra modules to be loaded"),
+-         cl::value_desc("input bitcode"));
+-
+-  cl::list<std::string>
+-  ExtraObjects("extra-object",
+-         cl::desc("Extra object files to be loaded"),
+-         cl::value_desc("input object"));
+-
+-  cl::list<std::string>
+-  ExtraArchives("extra-archive",
+-         cl::desc("Extra archive files to be loaded"),
+-         cl::value_desc("input archive"));
+-
+-  cl::opt<bool>
+-  EnableCacheManager("enable-cache-manager",
+-        cl::desc("Use cache manager to save/load mdoules"),
+-        cl::init(false));
+-
+-  cl::opt<std::string>
+-  ObjectCacheDir("object-cache-dir",
+-                  cl::desc("Directory to store cached object files "
+-                           "(must be user writable)"),
+-                  cl::init(""));
+-
+-  cl::opt<std::string>
+-  FakeArgv0("fake-argv0",
+-            cl::desc("Override the 'argv[0]' value passed into the executing"
+-                     " program"), cl::value_desc("executable"));
+-
+-  cl::opt<bool>
+-  DisableCoreFiles("disable-core-files", cl::Hidden,
+-                   cl::desc("Disable emission of core files if possible"));
+-
+-  cl::opt<bool>
+-  NoLazyCompilation("disable-lazy-compilation",
++static cl::opt<bool>
++NoLazyCompilation("disable-lazy-compilation",
+                   cl::desc("Disable JIT lazy compilation"),
+                   cl::init(false));
+ 
+-  cl::opt<Reloc::Model>
+-  RelocModel("relocation-model",
+-             cl::desc("Choose relocation model"),
+-             cl::init(Reloc::Default),
+-             cl::values(
+-            clEnumValN(Reloc::Default, "default",
+-                       "Target default relocation model"),
+-            clEnumValN(Reloc::Static, "static",
+-                       "Non-relocatable code"),
+-            clEnumValN(Reloc::PIC_, "pic",
+-                       "Fully relocatable, position independent code"),
+-            clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
+-                       "Relocatable external references, non-relocatable code"),
+-            clEnumValEnd));
+-
+-  cl::opt<llvm::CodeModel::Model>
+-  CMModel("code-model",
+-          cl::desc("Choose code model"),
+-          cl::init(CodeModel::JITDefault),
+-          cl::values(clEnumValN(CodeModel::JITDefault, "default",
+-                                "Target default JIT code model"),
+-                     clEnumValN(CodeModel::Small, "small",
+-                                "Small code model"),
+-                     clEnumValN(CodeModel::Kernel, "kernel",
+-                                "Kernel code model"),
+-                     clEnumValN(CodeModel::Medium, "medium",
+-                                "Medium code model"),
+-                     clEnumValN(CodeModel::Large, "large",
+-                                "Large code model"),
+-                     clEnumValEnd));
+-
+-  cl::opt<bool>
+-  GenerateSoftFloatCalls("soft-float",
+-    cl::desc("Generate software floating point library calls"),
+-    cl::init(false));
+-
+-  cl::opt<llvm::FloatABI::ABIType>
+-  FloatABIForCalls("float-abi",
+-                   cl::desc("Choose float ABI type"),
+-                   cl::init(FloatABI::Default),
+-                   cl::values(
+-                     clEnumValN(FloatABI::Default, "default",
+-                                "Target default float ABI type"),
+-                     clEnumValN(FloatABI::Soft, "soft",
+-                                "Soft float ABI (implied by -soft-float)"),
+-                     clEnumValN(FloatABI::Hard, "hard",
+-                                "Hard float ABI (uses FP registers)"),
+-                     clEnumValEnd));
+-}
++static cl::opt<Reloc::Model>
++RelocModel("relocation-model",
++           cl::desc("Choose relocation model"),
++           cl::init(Reloc::Default),
++           cl::values(
++             clEnumValN(Reloc::Default, "default",
++                        "Target default relocation model"),
++             clEnumValN(Reloc::Static, "static",
++                        "Non-relocatable code"),
++             clEnumValN(Reloc::PIC_, "pic",
++                        "Fully relocatable, position independent code"),
++             clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
++                        "Relocatable external references, non-relocatable code"),
++             clEnumValEnd));
++
++static cl::opt<llvm::CodeModel::Model>
++CMModel("code-model",
++        cl::desc("Choose code model"),
++        cl::init(CodeModel::JITDefault),
++        cl::values(clEnumValN(CodeModel::JITDefault, "default",
++                              "Target default JIT code model"),
++                   clEnumValN(CodeModel::Small, "small",
++                              "Small code model"),
++                   clEnumValN(CodeModel::Kernel, "kernel",
++                              "Kernel code model"),
++                   clEnumValN(CodeModel::Medium, "medium",
++                              "Medium code model"),
++                   clEnumValN(CodeModel::Large, "large",
++                              "Large code model"),
++                   clEnumValEnd));
++
++static cl::opt<bool>
++GenerateSoftFloatCalls("soft-float",
++                       cl::desc("Generate software floating point library calls"),
++                       cl::init(false));
++
++static cl::opt<llvm::FloatABI::ABIType>
++FloatABIForCalls("float-abi",
++                 cl::desc("Choose float ABI type"),
++                 cl::init(FloatABI::Default),
++                 cl::values(
++                   clEnumValN(FloatABI::Default, "default",
++                              "Target default float ABI type"),
++                   clEnumValN(FloatABI::Soft, "soft",
++                              "Soft float ABI (implied by -soft-float)"),
++                   clEnumValN(FloatABI::Hard, "hard",
++                              "Hard float ABI (uses FP registers)"),
++                   clEnumValEnd));
+ 
+ //===----------------------------------------------------------------------===//
+ // Object cache
+@@ -429,17 +434,17 @@
+   }
+ 
+   std::string ErrorMsg;
+-  EngineBuilder builder(std::move(Owner));
+-  builder.setMArch(MArch);
+-  builder.setMCPU(MCPU);
+-  builder.setMAttrs(MAttrs);
+-  builder.setRelocationModel(RelocModel);
+-  builder.setCodeModel(CMModel);
+-  builder.setErrorStr(&ErrorMsg);
+-  builder.setEngineKind(ForceInterpreter
++  EngineBuilder Builder(std::move(Owner));
++  Builder.setMArch(MArch);
++  Builder.setMCPU(MCPU);
++  Builder.setMAttrs(MAttrs);
++  Builder.setRelocationModel(RelocModel);
++  Builder.setCodeModel(CMModel);
++  Builder.setErrorStr(&ErrorMsg);
++  Builder.setEngineKind(ForceInterpreter
+                         ? EngineKind::Interpreter
+                         : EngineKind::JIT);
+-  builder.setUseOrcMCJITReplacement(UseJITKind == JITKind::OrcMCJITReplacement);
++  Builder.setUseOrcMCJITReplacement(UseJITKind == JITKind::OrcMCJITReplacement);
+ 
+   // If we are supposed to override the target triple, do so now.
+   if (!TargetTriple.empty())
+@@ -455,7 +460,7 @@
+ 
+     // Deliberately construct a temp std::unique_ptr to pass in. Do not null out
+     // RTDyldMM: We still use it below, even though we don't own it.
+-    builder.setMCJITMemoryManager(
++    Builder.setMCJITMemoryManager(
+       std::unique_ptr<RTDyldMemoryManager>(RTDyldMM));
+   } else if (RemoteMCJIT) {
+     errs() << "error: Remote process execution does not work with the "
+@@ -463,15 +468,15 @@
+     exit(1);
+   }
+ 
+-  builder.setOptLevel(getOptLevel());
++  Builder.setOptLevel(getOptLevel());
+ 
+   TargetOptions Options;
+   if (FloatABIForCalls != FloatABI::Default)
+     Options.FloatABIType = FloatABIForCalls;
+ 
+-  builder.setTargetOptions(Options);
++  Builder.setTargetOptions(Options);
+ 
+-  EE = builder.create();
++  EE = Builder.create();
+   if (!EE) {
+     if (!ErrorMsg.empty())
+       errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
+@@ -550,12 +555,16 @@
+     errs() << "warning: remote mcjit does not support lazy compilation\n";
+     NoLazyCompilation = true;
+   }
++
+   EE->DisableLazyCompilation(NoLazyCompilation);
+ 
++  std::string Argv0;
++  std::vector<std::string> ArgvVector;
++
+   // If the user specifically requested an argv[0] to pass into the program,
+   // do it now.
+-  if (!FakeArgv0.empty()) {
+-    InputFile = static_cast<std::string>(FakeArgv0);
++  if (!FakeArgv0.getValue().empty()) {
++    InputFile.setValue(FakeArgv0.getValue());
+   } else {
+     // Otherwise, if there is a .bc suffix on the executable strip it off, it
+     // might confuse the program.
+@@ -563,25 +572,59 @@
+       InputFile.erase(InputFile.length() - 3);
+   }
+ 
++  Argv0 = InputFile.getValue();
++  ArgvVector.push_back(Argv0);
++
+   // Add the module's name to the start of the vector of arguments to main().
+-  InputArgv.insert(InputArgv.begin(), InputFile);
++  ArgvVector.insert(ArgvVector.end(), InputArgv.begin(), InputArgv.end());
+ 
+   // Call the main function from M as if its signature were:
+   //   int main (int argc, char **argv, const char **envp)
+   // using the contents of Args to determine argc & argv, and the contents of
+   // EnvVars to determine envp.
+   //
+-  Function *EntryFn = Mod->getFunction(EntryFunc);
++  std::string EntryFuncName = EntryFunc.getValue();
++  LLVMContext &Ctx = Mod->getContext();
++
++  llvm::Type *PPInt8ArgvTy = llvm::Type::getInt8PtrTy(Ctx)->getPointerTo();
++  llvm::Type *PPInt8EnvpTy = llvm::Type::getInt8PtrTy(Ctx)->getPointerTo();
++  llvm::IntegerType *PInt32RetTy = llvm::Type::getInt32Ty(Ctx);
++  llvm::IntegerType *PInt32ArgcTy = llvm::Type::getInt32Ty(Ctx);
++  llvm::Type *VoidRetTy = llvm::Type::getVoidTy(Ctx);
++  llvm::Type *VoidArgTy = llvm::Type::getVoidTy(Ctx);
++
++  Constant *EC = Mod->getOrInsertFunction("main",
++                                          PInt32RetTy, PInt32ArgcTy,
++                                          PPInt8ArgvTy, PPInt8EnvpTy,
++                                          nullptr);
++
++  Function *EntryFn = dyn_cast<Function>(EC);
++  if (!EntryFn) {
++    EC = Mod->getOrInsertFunction("main", PInt32RetTy, PInt32ArgcTy,
++                                       PPInt8ArgvTy, nullptr);
++    EntryFn = dyn_cast<Function>(EC);
++  }
++
++  if (!EntryFn) {
++    EC = Mod->getOrInsertFunction("main", PInt32RetTy, nullptr);
++    EntryFn = dyn_cast<Function>(EC);
++  }
++
++  if (!EntryFn) {
++    EC = Mod->getOrInsertFunction("main", VoidRetTy, nullptr);
++    EntryFn = dyn_cast<Function>(EC);
++  }
++
+   if (!EntryFn) {
+     errs() << '\'' << EntryFunc << "\' function not found in module.\n";
+     return -1;
+   }
+ 
++  EntryFn->setCallingConv(CallingConv::C);
++
+   // Reset errno to zero on entry to main.
+   errno = 0;
+ 
+-  int Result;
+-
+   // Sanity check use of remote-jit: LLI currently only supports use of the
+   // remote JIT on Unix platforms.
+   if (RemoteMCJIT) {
+@@ -601,29 +644,48 @@
+ #endif
+   }
+ 
++  int Result = 0;
++  Constant *Exit = nullptr;
++  Function *ExitFn = nullptr;
++  void *EntryFnPtr = nullptr;
++  void *ExitFnPtr = nullptr;
++
+   if (!RemoteMCJIT) {
+     // If the program doesn't explicitly call exit, we will need the Exit
+     // function later on to make an explicit call, so get the function now.
+-    Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
+-                                                      Type::getInt32Ty(Context),
+-                                                      nullptr);
++    Exit = Mod->getOrInsertFunction("exit",
++                                    Type::getVoidTy(Context),
++                                    Type::getInt32Ty(Context),
++                                    nullptr);
++    assert(Exit && "Could not create an exit(2) Constant!");
++
++    ExitFn = cast_or_null<Function>(Exit);
++    assert(ExitFn && "Could not create an exit(2) Function!");
++
++    ExitFnPtr = EE->getPointerToFunction(ExitFn);
++    assert(ExitFnPtr && "Could not retrieve an exit(2) Function pointer!");
++    (void) ExitFnPtr;
+ 
+     // Run static constructors.
+     if (!ForceInterpreter) {
+       // Give MCJIT a chance to apply relocations and set page permissions.
+       EE->finalizeObject();
+     }
++
+     EE->runStaticConstructorsDestructors(false);
+ 
+     // Trigger compilation separately so code regions that need to be
+     // invalidated will be known.
+-    (void)EE->getPointerToFunction(EntryFn);
++    EntryFnPtr = EE->getPointerToFunction(EntryFn);
++    assert(EntryFnPtr && "Could not retrieve a main(2) Function pointer!");
++    (void) EntryFnPtr;
++
+     // Clear instruction cache before code will be executed.
+     if (RTDyldMM)
+       static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
+ 
+     // Run main.
+-    Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
++    Result = EE->runFunctionAsMain(EntryFn, ArgvVector, envp);
+ 
+     // Run static destructors.
+     EE->runStaticConstructorsDestructors(true);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/components/llvm/patches/034-solaris-clang-LLVM-python-perl-utils.patch	Thu Jul 28 16:25:34 2016 -0700
@@ -0,0 +1,89 @@
+# 24311726 clang's Perl and Python utilities should not use #!/usr/bin/env
+# We have our own rules about calling perl or python from a script.
+# Not for upstream because they have their own rules about the same.
+--- tools/clang/tools/clang-format/clang-format-diff.py	2015-10-07 09:00:20.000000000 -0800
++++ tools/clang/tools/clang-format/clang-format-diff.py	2016-07-06 15:23:00.886765925 -0800
+@@ -1,4 +1,4 @@
+-#!/usr/bin/env python
++#!/usr/bin/python2.7
+ #
+ #===- clang-format-diff.py - ClangFormat Diff Reformatter ----*- python -*--===#
+ #
+###
+--- utils/llvm-lit/llvm-lit.in	2015-02-13 23:11:25.000000000 -0800
++++ utils/llvm-lit/llvm-lit.in	2016-07-06 09:00:13.026877050 -0800
+@@ -1,4 +1,4 @@
+-#!/usr/bin/env python
++#!/usr/bin/python2.7
+ 
+ import os
+ import sys
+###
+--- tools/clang/tools/scan-view/bin/scan-view	2015-12-21 03:19:13.000000000 -0900
++++ tools/clang/tools/scan-view/bin/scan-view	2016-07-06 06:56:42.737952300 -0800
+@@ -1,4 +1,4 @@
+-#!/usr/bin/env python
++#!/usr/bin/python2.7
+ 
+ """The clang static analyzer results viewer.
+ """
+###
+--- tools/clang/tools/scan-build/bin/scan-build	2015-11-13 12:34:15.000000000 -0800
++++ tools/clang/tools/scan-build/bin/scan-build	2016-07-17 21:12:44.529864065 -0700
+@@ -1,4 +1,4 @@
+-#!/usr/bin/env perl
++#!/usr/bin/perl
+ #
+ #                     The LLVM Compiler Infrastructure
+ #
+@@ -1739,19 +1739,19 @@
+ 
+ # Determine the location of ccc-analyzer.
+ my $AbsRealBin = Cwd::realpath($RealBin);
+-my $Cmd = "$AbsRealBin/../libexec/ccc-analyzer";
+-my $CmdCXX = "$AbsRealBin/../libexec/c++-analyzer";
++my $Cmd = "$AbsRealBin/../lib/ccc-analyzer";
++my $CmdCXX = "$AbsRealBin/../lib/c++-analyzer";
+ 
+ # Portability: use less strict but portable check -e (file exists) instead of
+ # non-portable -x (file is executable). On some windows ports -x just checks
+ # file extension to determine if a file is executable (see Perl language
+ # reference, perlport)
+ if (!defined $Cmd || ! -e $Cmd) {
+-  $Cmd = "$AbsRealBin/ccc-analyzer";
++  $Cmd = "$AbsRealBin/../lib/ccc-analyzer";
+   DieDiag("'ccc-analyzer' does not exist at '$Cmd'\n") if(! -e $Cmd);
+ }
+ if (!defined $CmdCXX || ! -e $CmdCXX) {
+-  $CmdCXX = "$AbsRealBin/c++-analyzer";
++  $CmdCXX = "$AbsRealBin/../lib/c++-analyzer";
+   DieDiag("'c++-analyzer' does not exist at '$CmdCXX'\n") if(! -e $CmdCXX);
+ }
+ 
+###
+--- tools/clang/tools/clang-format/git-clang-format	2015-06-19 00:23:10.000000000 -0800
++++ tools/clang/tools/clang-format/git-clang-format	2016-07-06 07:00:51.876140590 -0800
+@@ -1,4 +1,4 @@
+-#!/usr/bin/env python
++#!/usr/bin/python2.7
+ #
+ #===- git-clang-format - ClangFormat Git Integration ---------*- python -*--===#
+ #
+###
+--- tools/clang/tools/scan-build/libexec/ccc-analyzer	2015-11-13 11:34:15.000000000 -0900
++++ tools/clang/tools/scan-build/libexec/ccc-analyzer	2016-07-06 15:30:08.133853080 -0800
+@@ -1,4 +1,4 @@
+-#!/usr/bin/env perl
++#!/usr/bin/perl
+ #
+ #                     The LLVM Compiler Infrastructure
+ #
+###
+--- tools/clang/tools/scan-build/libexec/c++-analyzer	2015-11-13 11:34:15.000000000 -0900
++++ tools/clang/tools/scan-build/libexec/c++-analyzer	2016-07-06 15:29:59.431752970 -0800
+@@ -1,4 +1,4 @@
+-#!/usr/bin/env perl
++#!/usr/bin/perl
+ 
+ use Cwd qw/ abs_path /;
+ use File::Basename qw/ dirname /;